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.
A flip changes a single 0 into a 1. You may use fewer than k flips.
Function Signature
def longest_ones(nums: list[int], k: int) -> int:
Rules
-
The answer is the length of the longest contiguous run of
1
s after the flips. If no run can be formed (for example
k = 0
and
nums
has no
1
), return 0.
Constraints
-
1 <= len(nums) <= 10^5
-
Each
nums[i]
is either
0
or
1
.
-
0 <= k <= len(nums)
Examples
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Flipping the zeros at indices 4 and 5 turns indices 4 to 9 into six consecutive 1s. Flipping indices 5 and 10 also gives a run of 6 (indices 5 to 10), and no choice of two flips does better.
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Flipping the zeros at indices 4, 5 and 9 turns indices 2 to 11 into ten consecutive 1s.
Input: nums = [0,0,0], k = 0
Output: 0
No flips are allowed and the array has no 1s, so there is no run.