Max Consecutive Ones III
Max Consecutive Ones III is LeetCode 1004 (Medium). nums holds only 0s and 1s, and you may flip at most k zeros into ones. Return the length of the longest run of consecutive 1s you can make.
- Using fewer than
kflips is allowed, andkcan be 0. - With up to 10⁵ elements, checking every subarray in O(n²) is too slow.
- 1 <= nums.length <= 10⁵
- nums[i] is either 0 or 1.
- 0 <= k <= nums.length
Intuition
The flipping is only a story. A stretch of the array can be turned into all 1s exactly when it contains at most k zeros. So the real task is: find the longest subarray with at most k zeros.
Keep a window [left, right] that always obeys that rule. Move right one step at a time; when the new element pushes the zero count above k, move left forward until a zero has left. For every right, left is then the furthest-left start that still works, so the window is the longest valid one ending at right, and the best of those windows is the answer.
"Longest subarray where some count stays within a budget" is a variable-size sliding window. Longest Repeating Character Replacement and Fruit Into Baskets have the same shape with a different count.
Approach
Before reading on, restate the flips as a condition on a subarray. Then decide what has to happen when one more element breaks that condition, and whether the left edge ever needs to move back. Aim for O(n) time and O(1) space.
Grow the window to the right
For each right, if nums[right] is 0, add 1 to zeros. The new element always joins the window, and the next step repairs the window if it now has too many zeros.
Shrink from the left until at most k zeros remain
While zeros > k, check nums[left]: if it is 0, subtract 1 from zeros. Then move left one step right. Any 1s in front of the first zero must leave too, because the window has to stay one unbroken stretch.
Record the window length
Now the window [left, right] has at most k zeros, so all of it can be flipped into 1s. Update best with right - left + 1.
Why left never has to move back
If the window from left held too many zeros for this right, it still holds too many for every later right, because adding elements never removes a zero. No start that was dropped can come back, so both pointers only move forward and each element is added and removed at most once.
Code in Python, C++ and Java
Common pitfalls
Recording the length before the window is repaired
best = max(best, right - left + 1)
while zeros > k:
...while zeros > k:
...
best = max(best, right - left + 1)The length is then measured while the window can still hold k + 1 zeros. For [1, 0, 0, 1] with k = 1, the window [1, 0, 0] is recorded and the answer comes out as 3 instead of 2.
Returning len(nums) - left with a while loop
while zeros > k: ... # no best return len(nums) - left
best = max(best, right - left + 1) ... return best
len(nums) - left is only correct for the version that moves left at most one step per element, where the window never shrinks. With a while loop the final window can be much shorter than the best one: [1, 1, 1, 0, 0] with k = 0 returns 0 instead of 3.
Edge cases
zeros never passes k, left stays at 0, and the answer is the full length of nums.
Each zero is removed as soon as it enters, so the window is always empty and best stays 0.
Complexity
right visits each element once, and left only moves forward, so it also passes each element at most once. Only three counters are stored.Max Consecutive Ones III FAQ
How is this different from Max Consecutive Ones and Max Consecutive Ones II?
Max Consecutive Ones (LeetCode 485) allows no flips, and Max Consecutive Ones II (LeetCode 487) allows one. They are this problem with k = 0 and k = 1, so the same code solves both.
Is it a bug to shrink with if instead of while?
Not if you still keep best. With if, left moves at most one step per element, so the window never gets shorter: it grows when the new element fits and slides when it does not. Its length always equals the best length so far. The window can hold too many zeros at times, so it is only good for the length, not for reporting the actual subarray.
Is there a way to see the answer straight from the zeros?
Yes. List the zero positions with -1 added at the front and n at the end. A best window uses k zeros and stops just before the next one, so the answer is the largest gap z[i + k + 1] - z[i] - 1 over every i, or n if there are at most k zeros. It is a good way to check the sliding window by hand.
How do I find which zeros to flip?
Save left and right whenever best improves. The zeros inside that saved window are the ones to flip; there are at most k of them.