Max Consecutive Ones III
Problem
Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k zeros to ones.
Example 1
- Input
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2- Output
6- Why
- Flip the zeros at indices 5 and 10 to get 1, 1, 1, 1, 1, 1 from index 5 to 10.
Example 2
- Input
nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], k = 3- Output
10
Constraints
- 1 ≤ nums.length ≤ 10⁵
- nums[i] is 0 or 1.
- 0 ≤ k ≤ nums.length
Explanation
Rephrase it: find the longest subarray that contains at most k zeros. Those zeros are the ones you flip.
Grow the window on the right; whenever it holds more than k zeros, move the left edge forward until it is valid again.
Approach 1 · Naive
Every start, count zeros
- Time O(n²)
- Space O(1)
From each start, extend the end while the number of zeros stays within k.
- For each
i, setzeros = 0. - For
j ≥ i: count zeros; stop whenzeros > k; otherwise update the best withj - i + 1.
class Solution {
public int longestOnes(int[] nums, int k) {
int best = 0;
for (int i = 0; i < nums.length; i++) {
int zeros = 0;
for (int j = i; j < nums.length; j++) {
if (nums[j] == 0) {
zeros++;
}
if (zeros > k) {
break;
}
best = Math.max(best, j - i + 1);
}
}
return best;
}
}class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
best = 0
for i in range(len(nums)):
zeros = 0
for j in range(i, len(nums)):
zeros += nums[j] == 0
if zeros > k:
break
best = max(best, j - i + 1)
return bestApproach 2 · Optimal
Window with at most k zeros
- Time O(n)
- Space O(1)
Count zeros inside the window. Shrink from the left while there are too many, and record the window length after each step.
- Set
left = 0,zeros = 0. - For each
right: ifnums[right] == 0, incrementzeros. - While
zeros > k: ifnums[left] == 0, decrementzeros; incrementleft. - Update the best with
right - left + 1.
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0;
int zeros = 0;
int best = 0;
for (int 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;
}
}class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = zeros = best = 0
for right, num in enumerate(nums):
zeros += num == 0
while zeros > k:
zeros -= nums[left] == 0
left += 1
best = max(best, right - left + 1)
return bestComplexity compared
| Approach | Time | Space |
|---|---|---|
| Naive Every start, count zeros | O(n²) | O(1) |
| Optimal Window with at most k zeros | O(n) | O(1) |
Key takeaways
- Turning "flip at most k" into "window with at most k bad elements" is the key reframe.
Your notes
Saved in this browser as you type.
Solved it on your own?
Mark it done to track your progress, or star it to come back before an interview.