Problem Statement
Max Consecutive Ones III
You are given an array called nums that holds only 0s and 1s, and a number k. You are allowed to flip at most k of the 0s into 1s. After flipping, what is the longest run of 1s in a row you can make? Return that length.
Signals to notice
Brute force first
Try every subarray, count zeros, check if ≤ k. Each subarray independently counts its zeros. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Sliding window: expand right; when zero count exceeds k, shrink left. The window always contains at most k zeros. Track the maximum window length. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on nums=[1,1,1,0,0,0,1,1,1,1,0], k=2
r=2 (val 1): zeros=0, left=0, window [0..2] len=3 -> max_len=3 r=3 (val 0): zeros=1<=2, window [0..3] len=4 -> max_len=4 r=4 (val 0): zeros=2<=2, window [0..4] len=5 -> max_len=5 r=5 (val 0): zeros=3>2 -> shrink: nums[0..2]=1 skip, hit nums[3]=0 -> zeros=2, left=4, window [4..5] len=2 r=6..9 (vals 1,1,1,1): zeros=2<=2, left=4, at r=9 window [4..9] len=6 -> max_len=6 r=10 (val 0): zeros=3>2 -> shrink: nums[4]=0 -> zeros=2, left=5, window [5..10] len=6 -> max_len stays 6 loop ends -> return max_len=6
What must stay true
The window represents a subarray where at most k zeros have been 'flipped' to ones. All elements in the window are either 1 or a flipped 0. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
left = 0, zeros = 0, max_len = 0
for right in 0..n-1:
if nums[right] == 0: zeros += 1
while zeros > k: if nums[left]==0: zeros -= 1; left += 1
max_len = max(max_len, right - left + 1)
return max_lenPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Actually flipping the zeros in the array — don't modify the array. Just count zeros in the window and pretend they're flipped. The fix is usually to return to the meaning of each move, not just the steps themselves.