Leetcode # 1493. Longest Subarray of 1’s After Deleting One Element

Problem

https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element

相關例題

Solution: Sliding Window

Time Complexity: O(len(nums))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def longestSubarray(self, nums: List[int]) -> int:
    ans = left = deleted_zeros = 0
    # counter = Counter()
    for right in range(len(nums)):
      if nums[right] == 0: deleted_zeros += 1
      # counter[nums[right]] += 1

      # while left <= right and counter[0] > 1:
      while left <= right and deleted_zeros > 1:
        # remove arr[left] from curr
        if nums[left] == 0: deleted_zeros -= 1
        # counter[nums[left]] -= 1
        left += 1

      # update ans
      # "(right - left) 1's" and "a 0 or 1"
      ans = max(ans, right - left)
    
    return ans

Last Updated on 2023/09/09 by A1go

目錄
Bitnami