← DiffPush

Fruit Into Baskets

Standard Bar Sliding Window · Medium Problems O(n) · O(1)

The Orchard Harvest Cart

A farm worker walks a single row of trees, each tree bearing exactly one fruit of a given type, and may carry only two crates — one per fruit type, but each with unlimited capacity. Starting anywhere and moving strictly rightward, they must pick from every tree they pass and stop the moment a third fruit type appears. The forecaster wants the largest haul achievable.

Input: An integer array fruits where fruits[i] is the fruit type of tree i.

Output: Return the maximum number of fruits collectible from one contiguous run of trees using at most two types.

Constraints

Examples

Example 1

Input: {"fruits":[2,1,2]}
Output: 3
Two types across three trees fit the two crates exactly.

Example 2

Input: {"fruits":[1,2,3,2,2]}
Output: 4
Starting at tree 1 lets the picker ride types 2 and 3 through four trees.

Solve this in your browser →

Also on LeetCode ↗