The most straightforward approach is to check every possible starting position and see how far we can extend while flipping at most k zeros. For each starting index, we move forward and count zeros. Once the count exceeds k, we stop and record the window length. This method explores all contiguous subarrays but performs redundant work by rescanning overlapping regions.
res to store the maximum length found.l, set a zero counter cnt to 0 and expand with pointer r:0 and cnt already equals k, stop expanding.0, increment cnt.r forward.res with r - l.res after checking all starting positions.We can precompute a prefix sum array that counts zeros up to each index. For any subarray from l to r, the number of zeros is simply prefix[r + 1] - prefix[l]. This allows us to quickly check if a window is valid (contains at most k zeros). For each starting position, we binary search for the farthest ending position where the zero count stays within the limit. This avoids the linear scan of the brute force approach.
prefix[i] stores the count of zeros in nums[0..i-1].l, binary search for the largest r such that prefix[r + 1] - prefix[l] <= k.res with r - l (the window length).res after processing all starting positions.class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + (1 if num == 0 else 0))
res = 0
for l in range(len(nums)):
low, high = l, len(nums)
while low < high:
mid = (low + high) // 2
if prefix[mid + 1] - prefix[l] <= k:
low = mid + 1
else:
high = mid
res = max(res, low - l)
return resA sliding window provides the optimal approach. We maintain a window that can contain at most k zeros. As we expand the right boundary, we decrement k for each zero encountered. When k goes negative, the window has too many zeros, so we shrink from the left until the window is valid again. The maximum window size seen during this process is our answer. Each element is processed at most twice, yielding linear time complexity.
l (left pointer) and res (result) to 0.r (right pointer):nums[r] is 0, decrement k.k < 0 (window is invalid):nums[l] is 0, increment k (restore the flip allowance).l forward.res with r - l + 1.res.k Without Restoring ItWhen using k directly as a counter (decrementing when encountering zeros), remember that this mutates the input parameter. If you need to use k again later or if the problem requires preserving it, use a separate variable. Additionally, when shrinking the window, you must restore k by incrementing it when a zero leaves the window.
The window should shrink when k < 0, meaning we have flipped more zeros than allowed. A common mistake is using k == 0 as the shrinking condition, which prevents the window from ever containing k zeros. The window is valid as long as k >= 0; only shrink when it becomes negative.
When k equals or exceeds the number of zeros in the array, the answer is simply the length of the entire array. While the sliding window approach handles this naturally, the brute force approach might have issues if not carefully implemented. Also, handle the case when the array is empty or contains only ones.