1004. Max Consecutive Ones III (easy solution to understand)

Sliding Window Approach:

The sliding window technique is employed to iterate through the array nums.
The window starts from the left (i) and expands towards the right (j).
The goal is to find the longest subarray with at most k 0s by adjusting the window intelligently.

Maintaining Count of 1s:

The code keeps track of the count of consecutive 1s (one) within the sliding window.
It also keeps track of the maximum count of consecutive 1s encountered so far (maxvalue).
Updating the Answer:

At each step, the code updates the length of the longest subarray with at most k 0s (ans) based on the current window.
It does this by comparing the length of the current subarray (j - i + 1) with the maximum count of consecutive 1s (maxvalue) and the allowed number of 0s (k).

Adjusting the Window:

If the current subarray has more than k 0s, the window needs to be adjusted to maintain the constraint.
This adjustment is done by incrementing i and decrementing one (if necessary), effectively shifting the window towards the right.

Returning the Result : variable "ans"

Finally, the code returns the length of the longest subarray with at most k 0s (ans).

Note
we does not change maxvalue variable value which keep the track of no.of ones because if we want longest subarray so or maxvalue should be high.

Time Complexity: O(n)

space Complexity:O(1)

code

class Solution {
public:

int longestOnes(vector<int>& nums, int k) {
     int i = 0;
     int j = 0;
     int ans = 0;
     int maxvalue = 0;
     int one = 0;
    
     while(j<nums.size()){
          if(nums[j]==1){
              one++;
              maxvalue = max(maxvalue,one);
          }
          if(j-i+1-maxvalue<=k) ans = max(ans,j-i+1);
          else{
              if(nums[i]==1) one--;
              i++;
          }
          j++;
     }

     return ans;
}

};

Comments (0)