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: Flip At Most One ZeroInput: [1,0,1,1,0]10110↓ Flip first zero ↓111104 consecutive 1'sCould also flip last zero for 3 consecutive 1'sOutput: 4 (maximum possible)
Understanding the Visualization
1
Input Array
Binary array with 0's and 1's
2
Find Best Flip
Identify optimal zero to flip for maximum consecutive 1's
3
Output Length
Return maximum possible consecutive 1's
Key Takeaway
🎯 Key Insight: Use sliding window to maintain at most one zero, maximizing consecutive 1's efficiently
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