LeetCode #1004 Medium

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 k flips is allowed, and k can be 0.
  • With up to 10⁵ elements, checking every subarray in O(n²) is too slow.
Constraints
  • 1 <= nums.length <= 10⁵
  • nums[i] is either 0 or 1.
  • 0 <= k <= nums.length
sliding-windowtwo-pointersarray
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestOnes(self, nums, k):
▶3 left = zeros = best = 0
▶4 for right in range(len(nums)):
▶5 if nums[right] == 0:
▶6 zeros += 1
▶7 while zeros > k:
▶8 if nums[left] == 0:
▶9 zeros -= 1
▶10 left += 1
▶11 best = max(best, right - left + 1)
▶12 return best
10111203040516171819010flips0 of 2 usedlength0best0empty window, budget of 2 flips
left0
zeros0
best0
Flipping zeros is the same as allowing up to 2 zeros inside a window, because every zero in it can be flipped. The window starts empty.
10111203040516171819010RLflips0 of 2 usedlength1best1add a 1 → length 1, new best
right0
zeros0
best1
Index 0 is a 1, so no flip is needed. The window 0 to 0 can become all 1s, so its length 1 is the new best.
10111203040516171819010RLflips0 of 2 usedlength2best2add a 1 → length 2, new best
right1
zeros0
best2
Index 1 is a 1, so no flip is needed. The window 0 to 1 can become all 1s, so its length 2 is the new best.
10111203040516171819010RLflips0 of 2 usedlength3best3add a 1 → length 3, new best
right2
zeros0
best3
Index 2 is a 1, so no flip is needed. The window 0 to 2 can become all 1s, so its length 3 is the new best.
10111203040516171819010RLflips01 of 2 usedlength4best4add a 0, flip 1 of 2 → length 4, new best
right3
zeros1
best4
Index 3 is a 0. It uses flip 1 of 2, which is still within the budget. The window 0 to 3 can become all 1s, so its length 4 is the new best.
10111203040516171819010RLflips002 of 2 usedlength5best5add a 0, flip 2 of 2 → length 5, new best
right4
zeros2
best5
Index 4 is a 0. It uses flip 2 of 2, which is still within the budget. The window 0 to 4 can become all 1s, so its length 5 is the new best.
10111203040516171819010RLflips0003 of 2 usedlength6best5add index 5 → 3 zeros, over the budget
right5
zeros3k = 2
Index 5 is a 0, so the window now holds 3 zeros, one more than the 2 flips allowed. It can no longer become all 1s, so the left edge has to move.
10111203040516171819010RLflips0003 of 2 usedlength5best5drop the 1 at index 0 → still 3 zeros
left1
zeros3
The element leaving is a 1, which does not free a flip. It still has to go: the window must stay one unbroken stretch, so every element before the first zero leaves with it.
10111203040516171819010RLflips0003 of 2 usedlength4best5drop the 1 at index 1 → still 3 zeros
left2
zeros3
The element leaving is a 1, which does not free a flip. It still has to go: the window must stay one unbroken stretch, so every element before the first zero leaves with it.
10111203040516171819010RLflips0003 of 2 usedlength3best5drop the 1 at index 2 → still 3 zeros
left3
zeros3
The element leaving is a 1, which does not free a flip. It still has to go: the window must stay one unbroken stretch, so every element before the first zero leaves with it.
10111203040516171819010RLflips002 of 2 usedlength2best5drop the 0 at index 3 → back to 2 zeros
left4
zeros2
The element leaving is a 0, so one flip is freed and the window is back within the budget of 2.
10111203040516171819010RLflips002 of 2 usedlength2best5length 2, best stays 5
length2
best5
The window from 4 to 5 is valid again. It is the longest valid window ending at 5, but it is not longer than the best of 5.
10111203040516171819010RLflips002 of 2 usedlength3best5add a 1 → length 3
right6
zeros2
best5
Index 6 is a 1, so no flip is needed. The window 4 to 6 can become all 1s, so its length 3 is checked against the best of 5.
10111203040516171819010RLflips002 of 2 usedlength4best5add a 1 → length 4
right7
zeros2
best5
Index 7 is a 1, so no flip is needed. The window 4 to 7 can become all 1s, so its length 4 is checked against the best of 5.
10111203040516171819010RLflips002 of 2 usedlength5best5add a 1 → length 5
right8
zeros2
best5
Index 8 is a 1, so no flip is needed. The window 4 to 8 can become all 1s, so its length 5 is checked against the best of 5.
10111203040516171819010RLflips002 of 2 usedlength6best6add a 1 → length 6, new best
right9
zeros2
best6
Index 9 is a 1, so no flip is needed. The window 4 to 9 can become all 1s, so its length 6 is the new best.
10111203040516171819010RLflips0003 of 2 usedlength7best6add index 10 → 3 zeros, over the budget
right10
zeros3k = 2
Index 10 is a 0, so the window now holds 3 zeros, one more than the 2 flips allowed. It can no longer become all 1s, so the left edge has to move.
10111203040516171819010RLflips002 of 2 usedlength6best6drop the 0 at index 4 → back to 2 zeros
left5
zeros2
The element leaving is a 0, so one flip is freed and the window is back within the budget of 2.
10111203040516171819010RLflips002 of 2 usedlength6best6length 6, best stays 6
length6
best6
The window from 5 to 10 is valid again. It is the longest valid window ending at 10, but it is not longer than the best of 6.
10111203040516171819010RLflips002 of 2 usedlength6best6answer: 6
return6
Every right end has been tried, and for each one the window was the longest valid stretch ending there. The longest of them has 6 elements, so 6 consecutive 1s is the most that 2 flips can make.
05

Common pitfalls

Recording the length before the window is repaired

✗ Wrong
best = max(best, right - left + 1)
while zeros > k:
    ...
✓ Right
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

✗ Wrong
while zeros > k: ...
# no best
return len(nums) - left
✓ Right
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.

06

Edge cases

k is at least the number of zeros

zeros never passes k, left stays at 0, and the answer is the full length of nums.

All zeros and k = 0

Each zero is removed as soon as it enters, so the window is always empty and best stays 0.

07

Complexity

Time
O(n)
Space
O(1)
right visits each element once, and left only moves forward, so it also passes each element at most once. Only three counters are stored.
08

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.