Given a binary array, find length of the longest subsequence such that there is no 0 after a 1.
Input : 1 1 0 1 Output : 3 Explanation : If we remove 0 from the array, then no zero comes right after one (satisfying the condition) and the maximum game left are 3 (i.e. 1 1 1) Input : 0 Output : 1 Explanation : Since he wants to save maximum game in the array. He doesn't remove any game.
Let’s find out how many zeros will be in this sequence and then take all ones which come after the last zero. On each step take the next zero from the beginning of the sequence and count ones after it. Update answer with the maximum value.
You can pre-calculate number of ones on suffix.
E.g. 0 1 0 0 1 1 1
After calculating the suffix the array becomes :
0 4 0 0 3 2 1
Move from start to end and each time zero is found in the array increment numberofzeros by 1. If the array[index] not zero then res = max(res, numberofzeros + value of array at that index).
And then after the loop : res = max(res, numberofzeros)
This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Longest Zig-Zag Subsequence
- Longest subsequence with a given AND value | O(N)
- Longest subsequence with a given AND value
- Longest Uncommon Subsequence
- Longest Bitonic Subsequence in O(n log n)
- Longest Increasing Odd Even Subsequence
- Longest Increasing Subsequence using BIT
- Longest Repeating Subsequence
- Longest Consecutive Subsequence
- Longest subsequence whose average is less than K
- Longest Common Subsequence | DP-4
- Longest Palindromic Subsequence | DP-12
- Longest Bitonic Subsequence | DP-15
- Longest Increasing Subsequence Size (N log N)
- Longest subsequence such that difference between adjacents is one | Set 2
- Length of Longest Balanced Subsequence
- Longest subsequence having equal numbers of 0 and 1
- Longest Subsequence where index of next element is arr[arr[i] + i]
- Longest Ordered Subsequence of Vowels