Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s.
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 26nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 310The window [L,R] always contains at most k zeros (which we can flip to 1s). When a new zero pushes us over budget, we slide L right until we're within budget again. The window size R−L+1 at each R gives the max window ending at R with at most k flips. We track the maximum over all R.
Checking every subarray and counting its zeros is O(n²). Notice that a window is valid exactly when it contains at most k zeros.
Grow a window to the right, and count the zeros inside it. When the zeros exceed k, shrink from the left until the window is valid again. The answer is the longest valid window seen.
At most k flips means a window with at most k zeros. Grow on the right, shrink on the left when the rule breaks.
Run the animation above on your own input, or watch the 1:42 video explanation of Max Consecutive Ones III with a dry run and Java code.