Leetcode 1004. Maximum number of consecutive 1s III (sliding window)

For a typical sliding window problem, we maintain a sliding window so that the number of 0s in the sliding window does not exceed K.

class Solution {
public:
    int longestOnes(vector<int>& A, int K) {
        int n = A.size(), res = 0, count =0;
        for(int i=0,j=0;j<n;j++){
            if(A[j]==0) count++;
            while(i<=j&&count>K){
                if(A[i]==0) count--;
                i++;
            }
            res = max(res,j-i+1);
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/113855800