Skip to content

Instantly share code, notes, and snippets.

@superzjn
Created September 9, 2022 02:01
Show Gist options
  • Save superzjn/20fdfe26402f13f4b33517c4934bc3dd to your computer and use it in GitHub Desktop.
Save superzjn/20fdfe26402f13f4b33517c4934bc3dd to your computer and use it in GitHub Desktop.
[Fruit Into Baskets] LeetCode 904 #SlidingWindow
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
fruit_num = {}
max_number, win_start = 0,0
for win_end in range(len(fruits)):
right_fruit = fruits[win_end]
if right_fruit not in fruit_num:
fruit_num[right_fruit] = 0
fruit_num[right_fruit] += 1
while(len(fruit_num) > 2):
left_fruit = fruits[win_start]
fruit_num[left_fruit] -= 1
if fruit_num[left_fruit] == 0:
del fruit_num[left_fruit]
win_start += 1
max_number = max(max_number, win_end - win_start + 1)
return max_number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment