Home
DSA Patterns
Sliding Window
Max Consecutive Ones III
Max Consecutive Ones III
Find the longest run of 1s after flipping at most k zeros, as the longest sliding window containing at most k zeros.
Problem Understanding
Max Consecutive Ones III: given a binary array and an integer k, return the maximum number of consecutive 1s you can get if you may flip at most k zeros to 1.
Example: nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2 returns 6: flip the two zeros at indices 4 and 5.
The Intuition: A Window With a Zero Budget
Don't actually flip anything. A run of 1s after flipping is just a window of the original array that holds at most k zeros; those zeros are the ones you would flip. So look for the longest such window with a variable-size sliding window:
- Extend
right, counting zeros as they enter. - If the count goes above
k, moveleftforward until a zero leaves. - The window is valid again; record
right − left + 1if it is the longest.
Each index enters and leaves at most once, so this is O(n). The same "budget" shape appears in Longest Repeating Character Replacement, where the budget is replacements instead of zeros.
Interactive Walkthrough
The window L..R is shaded and the zeros inside it are dashed amber: those are the flips being spent. Watch the window slide forward whenever one zero too many comes in.
Dry Run Table
Input: [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2
| right | Window | Zeros | Length |
|---|---|---|---|
| 4 | 0..4 | 2 | 5 |
| 5 | 4..5 after shrinking past index 3 | 2 | 2 |
| 9 | 4..9 | 2 | 6 |
| 10 | 5..10 after shrinking past index 4 | 2 | 6 |
Return 6.
The Solution Template
Variable-size window with at most k zeros.
Max Consecutive Ones III Code
1var longestOnes = function(nums, k) {2 let left = 0, zeros = 0, best = 0;3 for (let right = 0; right < nums.length; right++) {4 if (nums[right] === 0) zeros++;5 while (zeros > k) {6 if (nums[left] === 0) zeros--;7 left++;8 }9 best = Math.max(best, right - left + 1);10 }11 return best;12};
Edge Cases & Common Mistakes
- k = 0: the answer is the longest existing run of 1s.
- k ≥ number of zeros: the whole array works.
- All zeros: the answer is
min(k, n). - Actually flipping the array: unnecessary; counting zeros in the window is enough.
- Recording before shrinking: only record once
zeros ≤ k.
Summary
Flipping at most k zeros means finding the longest window with at most k zeros. Grow the window on the right, shrink from the left whenever the zero count passes k, and record the longest valid window. O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
