Visualize LeetCode 1004 step by step. Watch the sliding window expand right and shrink left to maintain at most K zeros, maximizing the window of 1s.
About this algorithm
You have an array of 0s and 1s and may flip at most k zeros into ones. The goal is the longest run of ones you can end up with, which is the same as the longest stretch of the array containing no more than k zeros. A window that grows on the right and shrinks on the left finds it in one pass.
This is the template for "longest stretch that stays within a budget": at most k zeros, at most k distinct characters, at most k replacements. The window size is not given, which is what separates it from the fixed window page. Compared with min window sum, the goal is reversed: that page wants the shortest window that reaches a total, so it shrinks as soon as the window is good, while this one shrinks only when the window breaks the rule and records the length after every step.
Move right across the array one cell at a time. If the new cell is a 0, add one to the zero count.
While the window holds more than k zeros, move left forward. If the cell leaving is a 0, take one off the zero count.
The window from left to right now has at most k zeros, so every zero in it can be flipped. Its length is right - left + 1; keep the largest seen.
When right reaches the end, the largest length is the answer. Each cell joins the window once and leaves it at most once.
The page loads [1, 1, 0, 0, 1, 1, 0, 1, 1, 1] with k = 2. The window grows over indices 0 to 5 using both flips on the zeros at 2 and 3, reaching length 6. Index 6 is a third zero, one too many, so left moves: it drops the 1 at index 0, the 1 at index 1, and then the 0 at index 2, which brings the count back to 2 with left at 3. Adding indices 7 and 8 gives lengths 5 and 6, which only tie the best. Adding index 9 makes the window 3 to 9, length 7, a new best. The answer is 7: flip the zeros at 3 and 6 to get 1 1 1 1 1 1 1.
Some solutions never shrink by more than one cell: when the budget breaks they move left once and let the window slide at its best size. The final answer is the same, but the window on screen is not always valid, which is why this page uses the while loop.
Time: right passes each index once and left passes each index at most once, so about 2n moves in total. Space: two indices, the zero count and the best length.