904. Fruit Into Baskets
Asked at 13Amazon65Google52Bloomberg49Microsoft36Meta36Adobe74tcs36Salesforce28ServiceNow55Expedia54Zoho52Netflix49TikTok35
Problem
Trees stand in a row; fruits[i] is the type of fruit tree i grows. With two baskets that each hold one fruit type (any amount), start at any tree and pick one fruit from every tree moving right, stopping when a fruit fits no basket. Return the most fruit you can pick, i.e. the longest subarray with at most two distinct values.
Example: [1,2,3,2,2] → 4 ([2,3,2,2])
Constraints: n ≤ 10⁵.
= longest window with at most 2 distinct values. Count fruits in the window; shrink while more than 2 types.
Complexity: O(n).
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
cnt = defaultdict(int)
l = best = 0
for r, f in enumerate(fruits):
cnt[f] += 1
while len(cnt) > 2:
cnt[fruits[l]] -= 1
if cnt[fruits[l]] == 0:
del cnt[fruits[l]]
l += 1
best = max(best, r - l + 1)
return best
assert Solution().totalFruit([1, 2, 1]) == 3
assert Solution().totalFruit([0, 1, 2, 2]) == 3
assert Solution().totalFruit([1, 2, 3, 2, 2]) == 4
class Solution {
public int totalFruit(int[] fruits) {
Map<Integer, Integer> cnt = new HashMap<>();
int l = 0, best = 0;
for (int r = 0; r < fruits.length; r++) {
cnt.merge(fruits[r], 1, Integer::sum);
while (cnt.size() > 2) {
if (cnt.merge(fruits[l], -1, Integer::sum) == 0) cnt.remove(fruits[l]);
l++;
}
best = Math.max(best, r - l + 1);
}
return best;
}
}
func totalFruit(fruits []int) int {
cnt := map[int]int{}
l, best := 0, 0
for r, f := range fruits {
cnt[f]++
for len(cnt) > 2 {
cnt[fruits[l]]--
if cnt[fruits[l]] == 0 {
delete(cnt, fruits[l])
}
l++
}
best = max(best, r-l+1)
}
return best
}