Sliding Window Longest or shortest window
176. Fruit Into Baskets
A row of trees stands along a path, numbered from 0 on the left. Tree i grows fruit of type fruits[i].
Equal numbers are the same type, and different numbers are different types.
You carry two baskets. A basket holds as much fruit as you like, but all of it must be of one type. You choose any tree to start at and walk to the right. At every tree, the first one included, you pick exactly one fruit and put it in a basket. You cannot skip a tree. The walk stops at the first tree whose fruit fits in neither basket, and you take nothing from that tree. It also stops at the end of the row.
Return the largest number of fruits you can collect.
Example 1
Input: fruits = [4, 7, 4, 2, 2, 4, 2, 9, 9]
5Explanation: Start at tree 2 and collect 4, 2, 2, 4, 2, with the 4s in one basket and the 2s in the other. Tree 7
holds a 9, which fits in neither, so the walk stops there. Starting at tree 0 collects only 3.
Example 2
Input: fruits = [6, 6, 6, 6]
4Explanation: Every tree grows the same type, so one basket takes all four fruits.
Example 3
Input: fruits = [-3, 0, -3, 5, 0, 0, -3, 0]
4Explanation: Start at tree 4 and collect 0, 0, -3, 0, up to the end of the row. A negative number is a type like
any other.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ fruits.length ≤ 105-109 ≤ fruits[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.