Fruit Into Baskets

Finding Longest Subarrays (Standard Sliding Window) DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Fruit Into Baskets problem (Sliding Window for maximum subarray with constraints), Arrays, Sliding Window, Hash Map, Frequency Counting, Two Pointers, Optimization, Time Complexity, Space Complexity, complexity analysis, sliding window, subarray/substring, frequency counting, hash map, two pointer technique, Frequency in Window.

Fruit Into Baskets You are an agricultural expert tasked with optimizing fruit collection. You have a long row of fruit trees, and each tree produces fruit of a specific type. You have two baskets, and each basket can only hold fruits of a single type. There is no limit on the amount of fruit a basket can hold, but each basket must contain only one distinct type of fruit. You start picking from any tree of your choice, but once you start, you must pick exactly one fruit from every tree (if you move to it) until you cannot pick any more fruit. This means you must pick fruits in a continuous sequence. You stop when you encounter a third distinct type of fruit. Your goal is to find the maximum number of fruits you can collect. Input Specification: The input consists of a single line containing a list of integers fruits, where fruits[i] represents the type of fruit the i th tree produces. Output Specification: Output a single integer representing the maximum number of fruits you can collect. Constraints: 1 <= fruits.length <= 10^5 0 <= fruits[i] < fruits.length Sample Test Cases: Sample Input 1: Sample Output 1: Explanation 1: We can pick from all three trees. The sequence [1,2,1] contains only two distinct fruit types (1 and 2). Sample Input 2: Sample Output 2: Explanation 2: We can pick from [1,2,2]. Starting at index 1, we collect fruits of type 1 and 2. This sequence has a length of 3. Sample Input 3: Sample Output 3: Explanation 3: We can pick from [2,3,2,2]. Starting at index 1, we collect fruits of type 2 and 3. This sequence has a length of 4. Difficulty: Medium