O(n) time complexity CPP solution


#1

`int Solution::solve(vector &A, int B) {
int n=A.size();
if(n==0) return 0;

int i=0,j=0,ans=0;

while(i<n-ans)
{
    j=i;
    int count=B;
    
    while((count || A[j]==1) && j<n)
    {
        if(A[j]==0) count--;
        j++;
    }
    ans=max(ans,j-i);
    i++;
}
return ans;

}`


#2

Same implementation but showing more than O(n) time complexity
int Solution::solve(vector &A, int B) {
int i=0, j=1, store=0, lenght, X, max_lenght=0, n=A.size();

while(i<n && j<n){
    if(A[i]==1){
        lenght=1, X=B;
        while(j<n && (X>0 || A[j]==1)){
            if(A[j]==0)
                X--;
                j++;lenght++;
        }
        if(lenght > max_lenght){
             max_lenght=lenght;
             if(X!=0)
             store=X;
        }
    }
    i++;
    j=i+1;
}

if(store!=0){
    return ((store+max_lenght)>n)?n:(store+max_lenght);
}
else return max_lenght;

}