ZhongKuo0228 / study

0 stars 0 forks source link

1493. Longest Subarray of 1's After Deleting One Element #75

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

sliding window

  1. left, right 雙指針形成 window
  2. 用 zero_count 來紀錄當前 window 是否有 zero
  3. 如果 zero 超過 1 個,代表無法透過刪除 element 來形成連續 1's subarray,這時要限縮 window
  4. 所求即為最大長度 - 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