This requires counting the number of consecutive ones in the array if you are allowed to have up to k non-zeroes consecutively. We can solve this with a sliding window + counting the number of zeroes. If we have <= k
zeroes, then we’re fine — we can count this. However, if there are more than k
zeroes, then we increment our left side, incrementing until all of our left side is taken care of.
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
l, zeroes, max_len = 0, 0, 0
for r, val in enumerate(nums):
if val == 0:
zeroes += 1
while zeroes > k:
if nums[l] == 0:
zeroes -= 1
l += 1
max_len = max(max_len, r - l + 1)
return max_len