Skip to content
Problem 904 · LeetCode 904(opens in a new tab)

Fruit Into Baskets

MediumArrays

An orchard has one row of trees. Tree i grows fruit of type fruits[i]. You carry two baskets, and each basket may hold only one type of fruit, as much of it as you like.

You choose a tree to start at, then walk right and take one fruit from each tree you pass, starting tree included. As soon as you reach a tree whose fruit has no basket left, you stop. Return the largest number of fruits you can collect.

Example 1

Input:  fruits = [4, 1, 4, 2, 2, 4]
Output: 4
Why:    start at index 2 and take 4, 2, 2, 4
2 more examples and the constraints

Example 2

Input:  fruits = [2, 2, 2]
Output: 3
Why:    one type fills one basket; take them all

Example 3

Input:  fruits = [0, 1, 2, 3]
Output: 2
Why:    the third tree always brings a third type

Constraints

  • 1 ≤ fruits.length ≤ 100,000
  • 0 ≤ fruits[i] < fruits.length

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every startO(n²)
  2. Sliding windowO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 treesVerdict
Try every startO(n²)
Too slow on long two-type rows
Sliding windowO(n)
Best; every tree in and out once

n = number of trees.

Edge cases to test

  • One tree. [0] gives 1.
  • Only one or two types. The whole row fits, so the answer is its length.
  • All types different. Any two neighbours fit, never three: the answer is 2.
  • A type returns after leaving. In [0, 1, 0, 2, 0, 2, 2, 1], type 0 stays in the window while 1 is dropped, giving 0, 2, 0, 2, 2.

Common mistakes

  • Keeping a type in the map at count 0, so the window thinks it still holds three types.
  • Measuring the window before shrinking it back to two types.
  • Jumping L straight to R when a third type arrives, which throws away the older type that is still in a valid run.

How to talk through it

  1. 1Clarify. Must the picked trees be next to each other? Is one basket enough if there is only one type?
  2. 2Restate it. Longest contiguous stretch with at most two distinct values.
  3. 3Give the brute force. Try each start and walk until a third type; O(n²) on a long two-type row.
  4. 4Code the window. Grow R, keep counts in a map, shrink L while the map has three keys, and track the best width.
  5. 5Test out loud. Run a single tree, all-different types and a type that comes back before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?