LeetCode 487: Max Consecutive Ones II

Problem Description

Explanation

To solve this problem, we can use a sliding window approach. We will keep track of the count of zeros in the current window and maintain a variable to store the maximum consecutive ones we can achieve after flipping at most one zero. Here is the algorithmic idea:

  1. Initialize pointers left and right to the start of the array.
  2. While iterating through the array using the right pointer, we will keep track of the count of zeros encountered.
  3. If the count of zeros exceeds 1, we will move the left pointer to shrink the window until the count of zeros is 1 or less.
  4. Calculate the maximum length of consecutive ones after flipping at most one zero by comparing it with the previous maximum.
  5. Continue this process until we reach the end of the array.

Time complexity: O(n) where n is the length of the input array. Space complexity: O(1)

Solutions

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int left = 0, right = 0, zeroCount = 0, maxConsecutive = 0;
        
        while (right < nums.length) {
            if (nums[right] == 0) {
                zeroCount++;
            }
            
            while (zeroCount > 1) {
                if (nums[left] == 0) {
                    zeroCount--;
                }
                left++;
            }
            
            maxConsecutive = Math.max(maxConsecutive, right - left + 1);
            right++;
        }
        
        return maxConsecutive;
    }
}

Loading editor...