如果 zero 超過 1 個,代表無法透過刪除 element 來形成連續 1's subarray,這時要限縮 window
所求即為最大長度 - 1
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
ans = left = zero_count = 0
for right in range(len(nums)):
if nums[right] == 0:
zero_count += 1
while zero_count > 1:
if nums[left] == 0:
zero_count -= 1
left += 1
ans = max(ans, right - left)
return ans
sliding window