[英]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.给出一个长度为 N(最多 10^5)的字符串,它只包含 0 和 1。我们必须从原始字符串中删除两个长度正好为 K 的子字符串,以最大化连续 1 的数量。
For example suppose the string is 1100110001and K=1.例如假设字符串是 1100110001 并且 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)所以我们可以删除两个长度为 1 的子字符串。 这里最好的选择是删除第 3 位和第 4 位的 0 并得到输出为 4(因为新字符串将是 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:对于每个索引i ,计算:
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.对于每个索引,这三个值很容易在恒定时间内从早期索引的值中计算出来,因此您可以在O(N)时间内一次性完成此操作。
For example, let BEST(i,r) be the best length immediately preceding position i after removing r substrings.例如,让BEST(i,r)是移除 r 个子串后紧邻位置 i 之前的最佳长度。 If i >= K , then you can remove a substring ending at i and have BEST(i,r) = BEST(iK,r-1) for r > 0 .
如果i >= K ,那么您可以删除以i结尾的子字符串,并为r > 0设置BEST(i,r) = BEST(iK,r-1) 。 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 .
如果string[i-1] = '1'那么你可以从前一个位置扩展序列并有BEST(i,r) = BEST(i-1,r)+1 。 Choose the best possibility for each i,r .
为每个i,r选择最佳可能性。
The largest value you find in step (3) is the answer.您在步骤 (3) 中找到的最大值就是答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.