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.
You can flip at most k zeros to ones. Equivalently: find the longest window containing at most k zeros. Sliding window with a "zeros count" tracks the constraint.
Expand right: if the new element is 0, increment zeros counter. When zeros > k, shrink from left: if the removed element was 0, decrement zeros. Record max window length at every step.
The window always represents the largest valid subarray ending at right. Shrinking only when the constraint is violated ensures we never miss a longer valid window.
O(N) time, because each element enters and leaves the window at most once. O(1) space: only two pointers and a zeros counter.
Generalizes to: longest window with at most k "bad" elements (any character, any condition). Same template applies to many LeetCode problems.