简体   繁体   中英

Maximum number of consecutive 1's in a string

A string of length N (can be upto 10^5) is given which consists of only 0 and 1. We have to remove two substrings of length exactly K from the original string to maximize the number of consecutive 1's.

For example suppose the string is 1100110001and K=1.

So we can remove two substrings of length 1. The best possible option here is to remove the 0's at 3rd place and 4th place and get the output as 4 (as the new string will be 11110001)

If I try brute force it'll timeout for sure. I don't know if sliding window will work or not. Can anyone give me any hint on how to proceed? I am not demanding the full answer obviously, just some hints will work for me. Thanks in advance :)

This has a pretty straightforward dynamic programming solution.

For each index i , calculate:

  1. The length of the sequence of 1s that immediately precedes it, if nothing has been removed;
  2. The longest sequence of 1s that could immediately precede it, if exactly one substring is removed before it; and
  3. The longest sequence of 1s that could immediately precede it, if exactly two substrings are removed before it.

For each index, these three values are easily calculated in constant time from the values for earlier indexes, so you can do this in a single pass in O(N) time.

For example, let BEST(i,r) be the best length immediately preceding position i after removing r substrings. If i >= K , then you can remove a substring ending at i and have BEST(i,r) = BEST(iK,r-1) for r > 0 . If string[i-1] = '1' then you could extend the sequence from the previous position and have BEST(i,r) = BEST(i-1,r)+1 . Choose the best possibility for each i,r .

The largest value you find in step (3) is the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM