Skip to content
Decoder

Fruit Into Baskets

Medium

Problem

Trees stand in a row and fruits[i] is the type of fruit on tree i. You have **two baskets, and each basket holds only one type** of fruit (as much of it as you like). You pick a starting tree and move right, taking one fruit from every tree, and you must stop at the first tree whose fruit fits neither basket. Return the most fruit you can collect.

In other words: find the longest contiguous subarray with at most 2 distinct values.

Example 1

Input
fruits = [1, 2, 1]
Output
3

Example 2

Input
fruits = [0, 1, 2, 2]
Output
3
Why
start at index 1: [1, 2, 2]

Example 3

Input
fruits = [1, 2, 3, 2, 2]
Output
4
Why
[2, 3, 2, 2]

Constraints

  • 1 <= fruits.length <= 10^5
  • 0 <= fruits[i] < fruits.length

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.