一道ACM题,求O(n) 算法
大意,给你一01串,你能够把其中的k个0改成一,求改变后连续1的最大数目
Description
You are given a 01 sequence whose size is n. you can change at most k 0 into 1 in the sequence.
Now I want to know how many consecutive 1 in the sequce at most after you do the change.
Input
The first of input is an integer t which stands for the number of test cases.
for each test case, the first line contains two number n, k ( 1 <= n <= 100000, 0 <= k <= n ).
the next contains n element of the sequence, whose value is 0 or 1. Output Output the answer in one line for each test case.
Simple Input
2
4 2
1 0 0 1
4 1
1 0 1 0
Simple Output
4
3
[解决办法]
刚AC的,热乎乎的。要做到O(n)最主要的办法就是下标不要回溯。
代码大意为2个下标l,h,h一直向前走,遇到1,则结果加1,遇到0则看看是否还有机会(t)补1.
如果有,t--。
如果没有,l++且如果a[l]为0的话,机会+1,下一次循环。
- C/C++ code
void max_01(int* a,int n,int t) { int l = 0,h = 0,res = 0,tmp = 0; while(h < n) { if(a[h] == 0) { if(t == 0) { --tmp; if(a[l++] == 0) ++t; continue; } --t; } ++h; ++tmp; if(res < tmp) res = tmp; } printf("%d\n",res); } int main() { int t,n,k,a[100001]; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&k); for(int i = 0 ; i < n ; ++ i) scanf("%d",&a[i]); max_01(a,n,k); } return 0; }