Max Consecutive Ones III
Max Consecutive Ones III
Problem: Given an array A of 0s and 1s, we may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1s.
int longestOnes(vector<int>& A, int K) {
int res=0;
int f=0;
int start=0;
for(int i=0;i<A.size();++i) {
f+=1-A[i];
// If flips exceed K, slide the window forward
while(f>K) if (A[start++]==0) --f;
// Record the maximum
res=max(res, i-start+1);
}
return res;
}#sliding-window