Tere bhai ka O(N) C++ solution no double loop


#1
int Solution::solve(vector<int> &A, int B) {
    int cnt = 0;
    for(int i=0;i<A.size();i++){
        if(A[i]==0){
            cnt++;
            if(cnt==B)
                return -1;
        }
        else 
            break;
    }
    cnt =0;
    for(int i=A.size()-1;i>=0;i--){
        if(A[i]==0){
            cnt++;
            if(cnt==B)
                return -1;
        }
        else 
            break;
    }
    cnt =0;
    for(int i=0;i<A.size();i++){
        if(A[i]==0){
            cnt++;
            if(cnt==B*2-1)
                return -1;
        }
        else 
            cnt =0;
    }
    if(A.size()%((2*B)-1)!=0)
        return (A.size()/((2*B)-1))+1;
    else 
        return A.size()/((2*B)-1);
}

#2

Giving wrong output for this input:
10 1 1 1 0 0 0 0 0 1 1
3
it should give -1 but giving 2
In the third loop instead of comparing cnt == B2 it should compare cnt == (B2)-1


#3

Yes brooo… Thanks brooo…


#4

This is wrong. For the input:
5 1 0 0 0 1
3
The output should be 2 while your code returns 1.