Posted on

Descripiton

Submission

class Solution {
public:
    int longestOnes(vector<int>& A, int K) {
        int res = 0;
        
        if(K == 0) {
            int begOne = -1;
            for(int i = 0; i < A.size(); ++i) {
                if(A[i] == 0) begOne = -1;
                else if(begOne == -1) {
                    begOne = i;
                }
                if(begOne != -1) {
                    int tmp = i - begOne + 1;
                    if(tmp > res) res = tmp;
                }
            }
            return res;
        }
        
        for(int i = 0, j = 0; j < A.size();) {
            for(; (K > 0 || A[j] > 0) && j < A.size(); ++j) {
                if(A[j] == 0) K--;
            }
            
            int tmp = j - i;
            if(tmp > res) res = tmp;
            
            for(; K == 0; ++i) {
                if(A[i] == 0) ++K;
            }
        }
        
        return res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *