LeetCode 487: Max Consecutive Ones II Solution

Master LeetCode problem 487 (Max Consecutive Ones II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

487. Max Consecutive Ones II

Problem Explanation

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)

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 487 (Max Consecutive Ones II)?

This page provides optimized solutions for LeetCode problem 487 (Max Consecutive Ones II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 487 (Max Consecutive Ones II)?

The time complexity for LeetCode 487 (Max Consecutive Ones II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 487 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 487 in Java, C++, or Python.

Back to LeetCode Solutions