Max Consecutive Ones II - Problem
Given a binary array nums containing only 0s and 1s, you have the power to flip at most one zero to become a one. Your goal is to find the maximum number of consecutive 1's you can achieve after performing this operation.
Think of it as optimizing a sequence - you can strategically choose which zero (if any) to flip to create the longest possible chain of ones. If the array contains no zeros, you simply return the length of the entire array.
Examples:
[1,0,1,1,0]→ Flip the first 0 →[1,1,1,1,0]→ Answer: 4[1,0,1,1,0,1]→ Flip the middle 0 →[1,0,1,1,1,1]→ Answer: 4
Input & Output
example_1.py — Standard Case
$
Input:
[1,0,1,1,0]
›
Output:
4
💡 Note:
Flip the first 0 to get [1,1,1,1,0], giving us 4 consecutive ones at the beginning
example_2.py — Multiple Options
$
Input:
[1,0,1,1,0,1]
›
Output:
4
💡 Note:
We can flip either the first 0 to get [1,1,1,1,0,1] or the second 0 to get [1,0,1,1,1,1]. Both give us 4 consecutive ones maximum
example_3.py — All Ones
$
Input:
[1,1,1]
›
Output:
3
💡 Note:
Array has no zeros to flip, so we return the length of the entire array
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Terrain
Look at your bridge sections and identify where the gaps are located
2
Use Sliding Window
Create a flexible measuring window that can contain at most one gap
3
Expand Wisely
Grow your window to include more sections, keeping track of gaps
4
Contract When Needed
When you encounter a second gap, shrink the window from the left
5
Track the Maximum
Remember the longest bridge you can build throughout the process
Key Takeaway
🎯 Key Insight: Instead of trying every possible flip position, use a sliding window that maintains at most one zero. This reduces the time complexity from O(n²) to O(n) while using constant space.
Time & Space Complexity
Time Complexity
O(n²)
For each of the n positions, we scan the entire array to find max consecutive ones
⚠ Quadratic Growth
Space Complexity
O(n)
We create copies of the array for each flip attempt
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
- You can flip at most one 0 to 1
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code