Max Consecutive Ones III: the skills you need first
Updated
LeetCode · medium · sliding window. Zeros are the budget. Too many zeros: slide left until you are back under k.
Skills this problem builds on
Stuck on Max Consecutive Ones III? It is usually one of these. Get each one solid and the solution stops being a trick.
- At most k zeros in the window
Count zeros in a[L..R]. Expand R (zeros += 1 if a[R]==0). While zeros > k, drop a[L] and decrement if it was 0. Valid windows have zeros ≤ k.
- Shrink while the window is invalid
While the window is invalid, exclude a[L] and L += 1. Stop when it becomes valid, or when the window is empty (R < L).
- Longest valid window expands greedily
For a longest-window problem, advance R whenever you can. Shrink L only when the new R makes the window invalid. Do not shrink a still-valid window to tidy it.
check which ones you have 10 minutes, free, no account.