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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code