Max Consecutive Ones III
Given a binary array and an integer k, return the longest run of 1s you can make by flipping at most k zeros . Treat zeros as a budget inside the window: grow right, and shrink left whenever the zero count exceeds k.
Constraints
- 1 ≤ nums.length ≤ 105
- numsi is either 0 or 1
- 0 ≤ k ≤ nums.length
Example
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 26Explanation Flip the two 0s at indices 5 and 4 (or nearby) to get a run of six 1s.
Window may hold at most k zeros
Two zeros so far; zeros = 2 <= k; best = 4.
What happens in this step
window = [0, 3] [1, 1, 0, 0] before: zeros = 0 (right = 1) right = 2: nums[2] = 0 → zeros = 1 right = 3: nums[3] = 0 → zeros = 2 Both zeros fit inside the k = 2 flip budget — window valid; best becomes 4.
Steps to visualize
- Grow right; if the new value is 0, increment the zero budget used.
- While zeros exceed k, advance left and decrement when leaving a zero.
- The window always represents a stretch fixable with at most k flips.
- Update best with the current window length after each adjustment.
- Continue until right reaches the end of the array.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Two zeros so far; zeros = 2 <= k; best = 4.
What happens in this step
window = [0, 3] [1, 1, 0, 0] before: zeros = 0 (right = 1) right = 2: nums[2] = 0 → zeros = 1 right = 3: nums[3] = 0 → zeros = 2 Both zeros fit inside the k = 2 flip budget — window valid; best becomes 4.
Solution
function longestOnes(nums, k) {
let left = 0;
let zeros = 0;
let best = 0;
for (let right = 0; right < nums.length; right++) {
if (nums[right] === 0) zeros++;
while (zeros > k) {
if (nums[left] === 0) zeros--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 | 6 | Docstring example |
nums = [1], k = 0 | 1 | Single one |
nums = [0, 0, 1, 1], k = 2 | 4 | k covers all zeroes |
nums = [1, 1, 1, 1], k = 0 | 4 | All ones |
nums = [0, 0, 0], k = 1 | 1 | All zeroes with k = 1 |
nums = [1, 0, 1, 1, 0, 1], k = 0 | 2 | k = 0 is plain max consecutive ones |
nums = [1,1,0,0,1,1,1,0,1,1], k = 2 | 7 | Walkthrough array best length 7 |