Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

40. Fruit Into Baskets

MediumDay 13 of 60Sliding Window

A row of trees is given as fruits, where fruits[i] is the type of fruit on tree i. You have two baskets, and each basket holds only one type of fruit (but any amount of it). Starting from any tree, you pick one fruit from every tree moving right, and you must stop at the first tree whose fruit fits in neither basket. Return the maximum number of fruits you can collect.

Example 1
Input: fruits = [1,2,1]
Output: 3
Only two types exist, so every tree can be picked.
Example 2
Input: fruits = [1,2,3,2,2]
Output: 4
Start at index 1 to pick [2,3,2,2].
Constraints
  • 1 <= fruits.length <= 10^5
  • 0 <= fruits[i] < fruits.length
Hints
Frequently asked at: Google, Amazon, Swiggy
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min