Fruit Into Baskets

Sliding Window / 2 Pointer Longest and Smallest Window Problems Hard
  • This problem is a real-world application of the sliding window algorithm in software development
  • The sliding window concept is widely used in various programming scenarios like real-time data streaming where the algorithm helps in managing the flow of information
  • It's also critical in developing systems that handle network traffic management, or even simpler applications such as text editing software for tasks like "find and replace" where the problem domain is huge, but the task can be minimized to a "window" of text

There is only one row of fruit trees on the farm, oriented left to right. An integer array called fruits represents the trees, where fruits[i] denotes the kind of fruit produced by the ith tree.


The goal is to gather as much fruit as possible, adhering to the owner's stringent rules:


1) There are two baskets available, and each basket can only contain one kind of fruit. The quantity of fruit each basket can contain is unlimited.

2) Start at any tree, but as you proceed to the right, select exactly one fruit from each tree, including the starting tree. One of the baskets must hold the harvested fruits.

3) Once reaching a tree with fruit that cannot fit into any basket, stop.


Return the maximum number of fruits that can be picked.

Examples:

Input : fruits = [1, 2, 1]

Output : 3

Explanation : We will start from first tree.

The first tree produces the fruit of kind '1' and we will put that in the first basket.

The second tree produces the fruit of kind '2' and we will put that in the second basket.

The third tree produces the fruit of kind '1' and we have first basket that is already holding fruit of kind '1'. So we will put it in first basket.

Hence we were able to collect total of 3 fruits.

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

Output : 4

Explanation : we will start from second tree.

The first basket contains fruits from second , fourth and fifth.

The second basket will contain fruit from third tree.

Hence we collected total of 4 fruits.

Input : fruits = [1, 2, 3, 4, 5]

Constraints

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length

Hints

  • Use a sliding window approach. Expand the window to include fruits from the current tree while ensuring the window contains fruits from no more than two different types. If the window contains more than two types, shrink it from the left until it satisfies the two-basket rule.
  • Use a hash map to keep track of the count of each fruit type in the current window. The hash map ensures you can quickly add or remove fruit types as the window expands or shrinks.

Company Tags

Morgan Stanley Swiggy AMD PayPal Intel Bungie OYO Rooms Broadcom Lyft Seagate Technology Docker PwC Epic Systems Optum Alibaba Zynga Philips Healthcare Roche Instacart Etsy MongoDB GE Healthcare Oracle HashiCorp Deloitte Google Microsoft Amazon Meta Apple Netflix Adobe