Fruit Into Baskets

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array nums where nums[i] is the type of fruit the ith tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules:

  • You only have two baskets, and each basket can only hold a single type of fruit.
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. You must stop when you encounter a tree with a fruit type that cannot fit into either basket.

Return the maximum number of fruits you can pick.

Examples

Example 1:

Input: nums = [1,2,1]

Output: 3

Explanation: We can pick from all 3 trees. The two types are {1, 2}.

Example 2:

Input: nums = [0,1,2,2]

Output: 3

Explanation: We can pick from trees [1,2,2] starting at index 1. The two types are {1, 2}.

Example 3:

Input: nums = [1,2,3,2,2]

Output: 4

Explanation: We can pick from trees [2,3,2,2] starting at index 1. The two types are {2, 3}.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] < nums.length
Source: Sliding Window pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle