Leetcode 940 Solution

This article provides solution to leetcode question 940 (fruit-into-baskets)

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

Solution

class Solution: def totalFruit(self, tree: List[int]) -> int: m = collections.defaultdict(int) l = 0 r = 0
ans = 0 while r < len(tree): while r < len(tree): if tree[r] in m or len(m) < 2: m[tree[r]] += 1 r += 1 else: break ans = max(r - l, ans)
while l < r: fruit = tree[l]
m[fruit] -= 1 l += 1
if m[fruit] == 0: del m[fruit] break
return ans