Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
k zeros. Track zeros — the count of 0s currently in your window. When zeros > k, your budget is exhausted and you must shrink.l and r. Advance r each iteration. If you encounter a 0, increment zeros. While zeros > k, move l right — if nums[l] == 0, decrement zeros. Then update res = max(res, r - l + 1).while loop, the window [l..r] is guaranteed to have at most k zeros — it's a valid window. Updating res here (outside the while loop) ensures you only record valid windows. Each element enters and leaves the window at most once, making this O(n).Imagine a data stream where 1 = valid packet and 0 = dropped packet. A network relay can "repair" at most k dropped packets using forward error correction. You want to find the longest uninterrupted data stream when you can tolerate (correct) at most k packet drops. The sliding window scans the stream in one pass, greedily maximizing the repaired run length.
The key insight: flipping at most k zeros is equivalent to maintaining a window with at most k zeros. We never actually flip — we just track the zero count in our window and shrink when it exceeds k.
l = 0, zeros = 0, res = 0.r: if nums[r] == 0, increment zeros.zeros > k: if nums[l] == 0, decrement zeros; increment l.res = max(res, r - l + 1).res.Each pointer moves at most n steps total, giving O(n) time and O(1) extra space. The window always contains a valid configuration of at most k flipped zeros.
Discussion
…