1004. Max Consecutive Ones III
Asked at 21Meta76Amazon57Microsoft53Google49Bloomberg46Tekion74EPAM Systems67Infosys61Yandex57DE Shaw38Goldman Sachs36LinkedIn83Citadel64Nutanix60IBM59Expedia54Adobe44Visa39Capital One35Salesforce28TikTok26
Problem
nums is a binary array. If you may flip at most k zeros to ones, what is the longest run of consecutive 1s you can get?
Example: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 → 6
Constraints: n ≤ 10⁵.
Longest window containing at most k zeros. Grow r; when zeros exceed k, move l until one zero leaves.
Complexity: O(n) time, O(1) space.
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
l = zeros = best = 0
for r, x in enumerate(nums):
zeros += x == 0
while zeros > k:
zeros -= nums[l] == 0
l += 1
best = max(best, r - l + 1)
return best
assert Solution().longestOnes([1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2) == 6
assert Solution().longestOnes([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], 3) == 10
class Solution {
public int longestOnes(int[] nums, int k) {
int l = 0, zeros = 0, best = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r] == 0) zeros++;
while (zeros > k) if (nums[l++] == 0) zeros--;
best = Math.max(best, r - l + 1);
}
return best;
}
}
func longestOnes(nums []int, k int) int {
l, zeros, best := 0, 0, 0
for r, x := range nums {
if x == 0 {
zeros++
}
for zeros > k {
if nums[l] == 0 {
zeros--
}
l++
}
best = max(best, r-l+1)
}
return best
}