Fruit Into Baskets
Find the longest contiguous subarray containing at most two distinct elements using a sliding window and frequency map.
01The problem
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i-th tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules:
- You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
- Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right.
- Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Return the maximum number of fruits you can pick.
| Input | Output | Why |
|---|---|---|
fruits = [1, 2, 1] | 3 | We can pick from all 3 trees |
fruits = [1, 2, 3, 2, 2] | 4 | Subarray [2, 3, 2, 2] contains types 2 and 3 |
fruits = [0, 1, 2, 2] | 3 | Subarray [1, 2, 2] contains types 1 and 2 |
fruits = [7] | 1 | Only one tree exists |
Constraints: 1 to 100,000 trees, 0 ≤ fruits[i] < fruits.length.
Loading the rest of the lesson…