Sliding window cpp implementation


#1

SLIDING WINDOW PROBLEM
#define ll long long int
int Solution::solve(vector &a, int k) {

ll n = a.size() ;
ll l=0, r=0, len=0, ans = INT_MIN ;
// run as a sliding window type
while(l<n && r<n){
    if(a[r] == 1){
        r++; // just move the right pointer ahead
        len++ ;
    }
    
    else{ // a[r] == 0 case
        // here also 2 case arises
        if(k){
            k-- ; // decrease k by 1 and make the flip happen
            r++ ;
            len++ ;
        }
        
        else{ // now we have to move our l pointer ahead this time
            if(a[l] == 0){
                k++ ;
                l++ ;
                len-- ;
            }
            else{ // a[l] == 1 case
                len-- ;
                l++ ;
            }
            
        }
    }
    
    ans = max(ans, len) ;
}

ans = max(ans, len) ;
    
return ans ;

}