SDE & MLE Prep

1004. Max Consecutive Ones III

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