Max Consecutive Ones III
Medium
Topics
Given a binary array nums and an integer target (the number of 0s you may flip to 1), return the maximum number of consecutive 1s achievable.
Example 1
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], target = 2 Output: 6
Example 2
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], target = 3 Output: 10
Constraints
- 1 <= nums.length <= 10^5
- nums[i] is 0 or 1
- 0 <= target <= nums.length
Editorial — intuition, approach, complexity and pitfalls
Intuition
Do not think about which zeros to flip. Reframe the question: the answer is the length of the longest window that contains at most target zeros. The flipping is a story told around that invariant — nothing is ever actually flipped.
Once stated that way it is the canonical variable-size sliding window. Extend the right edge unconditionally; pull the left edge in only while the invariant is violated. Every index enters the window once and leaves at most once, which is where the linear bound comes from.
Approach
- Advance
rone step and, ifnums[r]is a zero, increment the zero count. - While the count exceeds
target, advancel, decrementing the count only when the cell being left behind is a zero. - Record
r - l + 1as a candidate answer.
Dry Run
nums = [1,1,1,0,0,0,1,1,1,1,0] target = 2
r nums[r] zeros window len best
0 1 0 [0,0] 1 1
1 1 0 [0,1] 2 2
2 1 0 [0,2] 3 3
3 0 1 [0,3] 4 4
4 0 2 [0,4] 5 5
5 0 2 [4,5] 2 5 <- third zero arrives, left edge jumps past two cells
6 1 2 [4,6] 3 5
7 1 2 [4,7] 4 5
8 1 2 [4,8] 5 5
9 1 2 [4,9] 6 6
10 0 2 [5,10] 6 6
answer 6At r = 5 the budget is blown, so the left edge moves from 0 to 4 — past the two zeros at indices 3 and 4 — restoring the invariant in one shrink.
Complexity
- Time — O(n):
rmakes n moves andlmakes at most n, so at most 2n pointer steps in total. Each element is examined a constant number of times. - Space — O(1): three integers. Nothing proportional to the input is stored.
Common Pitfalls
- Trying to decide which zeros to flip, usually by sorting or by a greedy over zero positions. The reframing to at most
targetzeros in a window is the entire problem. - Decrementing the zero count on every left-edge move instead of only when leaving a zero. The count then drifts and the window grows without bound.
- Recomputing the number of zeros inside the window on each step, which quietly turns the solution into O(n²) while still passing small tests.
- Not checking
target = 0, where the problem degenerates to the longest run of ones. The same loop handles it, but it is worth saying so rather than special-casing it. - There is an equivalent non-shrinking variant: replace the
whilewith anifand returnlen(nums) - l. Because the window then never shrinks, its final size is the maximum. Checked against the shown solution on every binary array up to length 10 for everytarget, the two always agree — but only because the question asks for a maximum. Reuse that trick on a problem that needs the window contents and it breaks.
Full Solution — all languages
class Solution:
def longestOnes(self, nums, target):
l = zeros = best = 0
for r in range(len(nums)):
if nums[r] == 0:
zeros += 1
while zeros > target:
if nums[l] == 0:
zeros -= 1
l += 1
best = max(best, r - l + 1)
return bestimport java.util.*;
class Solution {
public int longestOnes(int[] nums, int target) {
int l = 0, zeros = 0, best = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r] == 0) zeros++;
while (zeros > target) {
if (nums[l] == 0) zeros--;
l++;
}
best = Math.max(best, r - l + 1);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestOnes(vector<int>& nums, int target) {
int l = 0, zeros = 0, best = 0;
for (int r = 0; r < (int)nums.size(); r++) {
if (nums[r] == 0) zeros++;
while (zeros > target) {
if (nums[l] == 0) zeros--;
l++;
}
best = max(best, r - l + 1);
}
return best;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var longestOnes = function(nums, target) {
let l = 0, zeros = 0, best = 0;
for (let r = 0; r < nums.length; r++) {
if (nums[r] === 0) zeros++;
while (zeros > target) {
if (nums[l] === 0) zeros--;
l++;
}
best = Math.max(best, r - l + 1);
}
return best;
};