Solving tips
- Restate 'flip at most k zeros' as 'longest window containing at most k zeros', the classic operation-budget-to-window translation.
- Maintain a running zero count; grow right unconditionally and shrink left while zeros > k, tracking the max window size.
- Validity (at most k zeros) is monotone under shrinking, so both pointers move forward only, giving O(n) time and O(1) space.
- Common pitfall: record best only after restoring validity, and decrement the zero count only when the element leaving left is actually a 0.
Problem
You are given a binary array nums (each element is 0 or 1) and an integer k. You may flip at most k zeros into ones. Return the length of the longest run of consecutive 1s achievable after the flips.
Reworded without flipping: find the longest contiguous subarray that contains at most k zeros β flipping exactly those zeros makes it all ones.
Examples
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0],k = 2β6β flip the zeros at indices 5 and 10, making indices 5β10 six consecutive 1s (flipping indices 4 and 5 instead also yields a run of 6).nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],k = 3β10β flip the zeros at indices 4, 5, and 9 to connect indices 2β11.nums = [0, 0, 0],k = 0β0β no flips allowed and no 1s present.
Constraints
1 <= len(nums) <= 10^5nums[i]is0or10 <= k <= len(nums)
Enumerating all O(nΒ²) subarrays and counting their zeros is ~10^10 steps at the top end; the expected solution is one O(n) pass.
Think about it first
Hint 1
Forget flipping β restate the goal: longest window containing at mostk zeros. Which single number summarizes a window for this test?
Hint 2
If a window has at mostk zeros, so does any window inside it; if it has more, so does any window around it. Monotone validity means two forward-only pointers suffice.
Hint 3
Keep a running count of zeros in the window. Advanceright each step (count the entering zero); while the count exceeds k, advance left (uncount the leaving zero). Track the largest window ever valid.