Longest Run of Ones After K Flips
Implement longestRunOfOnesAfterKFlips
You're given a binary array
nums and an integer k — you may flip up to k zeros to ones. Return the length of the longest contiguous run of 1s you can achieve.
Re-checking every possible starting point from scratch is wasteful: as the window slides forward, most of its elements stay the same. A variable-size sliding windowVariable-Size Sliding WindowA window whose right edge always advances, but whose left edge only advances when a constraint is violated — so the window grows and shrinks in response to what it currently holds, rather than staying a fixed size. tracks how many 0s the current window is "spending" as flips; whenever that count exceeds k, the left edge shrinks just enough to bring it back within budget, and every position is visited by each pointer at most once.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Example 2:
Input: nums = [1,0,1,1,0,1], k = 1
Output: 4
Example 3:
Input: nums = [0,0,0,1], k = 4
Output: 4
+ 8 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁵ - ●
nums[i] is either 0 or 1 - ●
0 ≤ k ≤ nums.length
nums =
[1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
k =
2