Fruit Into Baskets Problem
Fruit Into Baskets Problem — ExecCode Easy DSA Practice
Solve the Fruit Into Baskets problem on ExecCode. Free online easy DSA practice in Sliding Window. Write and run code in Java, C++, Python — no signup required to run.
Problem description
You are given a row of fruit trees where fruits[i] is the type of fruit at tree i. You may start at any tree and move only to the right, collecting exactly one fruit from each tree until you must stop. You have two baskets, and each basket can hold only one fruit type. Return the maximum number of fruits you can collect in one contiguous stretch. Model the chosen stretch as a window and keep a frequency map of fruit types inside it.
Examples
Input fruits = [1, 2, 1, 2, 3, 2, 2]; Output 4. Input fruits = [0, 1, 2, 2]; Output 3. Input fruits = [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]; Output 5
Constraints
1 ≤ fruits.length ≤ 10⁵ 0 ≤ fruits[i] < fruits.length
Practice Fruit Into Baskets free on ExecCode. Browse DSA problems, topic map, and placement guides.