LC 0904 [M] Fruit Into Baskets - ALawliet/algorithms GitHub Wiki
Problem: Longest Subarray With 2 Elements
Problem: "Start from any index, we can collect at most two types of fruits. What is the maximum amount"
Translation: Find out the longest length of subarrays with at most 2 different numbers
class Solution:
def totalFruit(self, tree):
count = defaultdict(int)
l = 0
for r, x in enumerate(tree):
count[x] += 1
if len(count) > 2:
count[tree[l]] -= 1
if count[tree[l]] == 0:
count.pop(tree[l])
l += 1
return r - l + 1