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.
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Longest subsequence with a given AND value
- Longest Zig-Zag Subsequence
- Longest subsequence with a given AND value | O(N)
- Longest subsequence whose average is less than K
- Longest Bitonic Subsequence in O(n log n)
- Longest Uncommon Subsequence
- Longest Increasing Subsequence using BIT
- Longest Palindromic Subsequence | DP-12
- Longest Common Subsequence | DP-4
- Longest Bitonic Subsequence | DP-15
- Longest Consecutive Subsequence
- Longest Repeating Subsequence
- Longest Increasing Odd Even Subsequence
- Longest Subsequence where index of next element is arr[arr[i] + i]