given a string consists only of 0s and 1s say 10101
how to find the length of the longest non decreasing sub-sequence??
for example,
for the string,
10101
the longest non decreasing sub sequences are
- 111
- 001
so you should output 3
for the string
101001
the longest non decreasing sub sequence is
- 0001
so you should output 4
how to find this??
how can this be done when we are provided with limits.sequence between the limit
for example
101001
limits [3,6]
the longest non decreasing sub sequence is
- 001
so you should output 3
can this be achieved in o(strlen)
Yes. Observe that the non-decreasing subsequences would have one of these three forms:
The first two forms can be easily checked in
O(1)by counting all zeros and by counting all ones.The last one is a bit harder: you need to go through the string keeping the counter of zeros that you’ve seen so far, along with the length of the longest string of
0...01...1form that you have discovered so far. At each step where you see1in the string, the length of the longest subsequence of the third form is the larger of the number of zeros plus one or the longest0...01...1sequence that you’ve seen so far plus one.Here is the implementation of the above approach in C:
maxis defined as follows:Here is a link to a demo on ideone.