Given a binary arraynumsand a non-negative integerk, return the longest contiguous run of ones obtainable by changing at mostkzeroes to ones.
A window can be changed into all ones exactly when it contains at most k zeroes. Each zero requires one flip, while a one requires none, so the algorithm only needs to count the zeroes currently inside the window.
Move right across the array. When the new value is zero, increase zero_count.
If zero_count becomes larger than k, moving right farther cannot repair the window because expanding never removes any of the zeroes already inside it. Move left forward until enough zeroes leave and zero_count <= k again.
Moving past a one changes the window boundaries but does not free a flip, so zero_count stays unchanged. Moving past a zero reduces zero_count by one.
Which range uses at most two flips?
- zero_count
- 0
- best_length
- 1
When shrinking stops, left is the earliest remaining start whose window ending at right uses at most k flips. Any start already passed by left was ruled out when its window contained too many zeroes, and expanding farther right cannot make that earlier start valid again.
Only after the window is valid should its length be compared with best_length.
In the implementation, zeros is the current zero_count, and res stores the best length found so far.
With k = 0, every zero makes the current range invalid until that zero leaves. The same loop finds the longest run already made entirely of ones.
right visits each array position once, and left moves only forward across at most the same n positions. Total time is O(n). The boundaries, zero count, and best length use O(1) auxiliary space.