Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Fruit Into Baskets

Medium
sliding-windowarrayhash-table

You walk along a row of trees; fruits[i] is the fruit type of the i-th tree. You have two baskets, each holding only one type. Starting anywhere, you pick one fruit per tree moving right, stopping when a tree's fruit fits neither basket. Return the maximum number of fruits you can collect — i.e. the longest subarray with at most two distinct values.

Input: one line of space-separated integers fruits. Output: the maximum number of fruits.

Example 1
Input:
1 2 1
Output:
3
Example 2
Input:
0 1 2 2
Output:
3

[1,2,2] uses two types.

Example 3
Input:
1 2 3 2 2
Output:
4

[2,3,2,2].

Constraints

  • 1 ≤ fruits.length ≤ 10^5
  • 0 ≤ fruits[i] ≤ 10^5
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.