Easy to understand C++ O(n) solution


#1
int Solution::solve(vector<int> &A, int B) {
    
    int max_len = 0, left = B, i = 0, len = 0, last_start = 0;
    
    while(i < A.size()) {
        while(i < A.size() && A[i] == 1){
            i++;
            len++;
        }
        while(i < A.size() && left > 0 && A[i] == 0) {
            left--;
            i++;
            len++;
        }
        if(i == A.size()) return max(max_len, len);
        if(left == 0 && A[i] == 0) {
            max_len = max(max_len, len);
            while(A[last_start] == 1 && last_start < i) {
                last_start++;
                len--;
            }
            if(A[last_start] == 0) {
                last_start++;
                left++;
                len--;
            }
        }
    }
    return max_len;
}