1004. Max Consecutive Ones III
https://leetcode.com/problems/max-consecutive-ones-iii/
Python
Sliding Window
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left, right = 0, 0
while right < len(nums):
k -= 1 - nums[right]
if k < 0:
k += 1 - nums[left]
left += 1
right += 1
return right - left
Prefix Sum
Solution from glfox
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
if not nums:
return 0
zero_idx = {i:-1 for i in range(-k, 1)}
ans, zeros = 0, 0
for i in range(len(nums)):
if nums[i] == 0:
zeros += 1
zero_idx[zeros] = i
ans = max(ans, i - zero_idx[zeros - k])
return ans