Leetcode # 904. Fruit Into Baskets

Problem

https://leetcode.com/problems/fruit-into-baskets

Solution: Sliding Window

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

class Solution:
  def totalFruit(self, fruits: List[int]) -> int:
    curr_fruits = Counter()
    ans = left = curr = 0
    for right in range(len(fruits)):
      curr = fruits[right]
      # do logic here to add arr[right] to curr
      curr_fruits[curr] += 1

      while len(curr_fruits) > 2:
        start = fruits[left]
        curr_fruits[start] -= 1
        if curr_fruits[start] == 0:
          curr_fruits.pop(start)
        left += 1
      # update ans
      ans = max(ans, right - left + 1)
      
    return ans
        

 

Last Updated on 2025/08/04 by A1go

目錄
Bitnami