Fruit Into Baskets in Java: Explanation & Practice

Maximum fruits you can collect with two baskets

Problem summary

You have two baskets and a row of fruit trees. Each basket can hold only one type of fruit. Find the maximum number of fruits you can collect.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] fruits = {1, 2, 1, 2, 3};
        
        // This is longest subarray with at most 2 distinct elements
        // Use sliding window with HashMap
        // Print: Max fruits: 4
    }
}

Expected output and test cases

  • [1,2,1,2,3] → [1,2,1,2]
    Max fruits: 4
  • [0,1,2,2] → [1,2,2]
    Max fruits: 3
  • [3,3,3,1,2,1,1,2,3,3,4]
    Max fruits: 5

Hints

  1. This is the same as longest substring with 2 distinct characters
  2. Use HashMap to track fruit types in current window
  3. If more than 2 types, shrink window from left
  4. Track maximum window size

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler