oneby7

Sliding Window Longest or shortest window

176. Fruit Into Baskets

Medium

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]

Output: 5

Explanation: 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]

Output: 4

Explanation: 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]

Output: 4

Explanation: 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.

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

Constraints

  • 1 ≤ fruits.length ≤ 105
  • -109 ≤ fruits[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.