Max Consecutive Ones II - Problem

Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.

You are allowed to flip at most one 0 to 1 to maximize the length of consecutive ones.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,0,1,1,0]
Output: 4
💡 Note: Flip the first zero: [1,1,1,1,0] gives 4 consecutive 1's. Or flip the last zero: [1,0,1,1,1] gives 3 consecutive 1's. Maximum is 4.
Example 2 — All Ones
$ Input: nums = [1,1,1]
Output: 3
💡 Note: Already all 1's, no flip needed. Length is 3.
Example 3 — Single Zero
$ Input: nums = [1,0,1]
Output: 3
💡 Note: Flip the zero: [1,1,1] gives 3 consecutive 1's.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Max Consecutive Ones II INPUT Binary Array nums: 0 1 2 3 4 1 0 1 1 0 = 1 (one) = 0 (zero) Constraints: - Flip at most ONE 0 to 1 - Maximize consecutive 1s nums = [1,0,1,1,0] Length: 5 elements ALGORITHM STEPS 1 Sliding Window Use left/right pointers 2 Track Zero Count Count zeros in window 3 Shrink if zeros > 1 Move left pointer right 4 Update Max Length Track maximum window Best Window Found: 1 0 flip 1 1 Window size = 4 FINAL RESULT After Flipping Index 1: 1 1 1 1 0 4 consecutive 1s Yellow = Flipped 0 to 1 Output: 4 OK - Verified! Max consecutive 1s = 4 Key Insight: The sliding window technique with at most one zero allowed maintains O(n) time complexity. When we encounter more than one zero in our window, we shrink from the left until we have at most one zero again. This simulates flipping exactly one zero to maximize consecutive 1s. TutorialsPoint - Max Consecutive Ones II | Optimal Solution (Sliding Window)
Asked in
Google 35 Facebook 28 Amazon 22
28.5K Views
Medium-High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen