04 Fruits into Baskets (medium) √

0

Problem Statement
Given an array of characters where each character represents a fruit tree, you are given two baskets, and your goal is to put maximum number of fruits in each basket. The only restriction is that each basket can have only one type of fruit.

You can start with any tree, but you can’t skip a tree once you have started. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.

Write a function to return the maximum number of fruits in both baskets.

Example 1:

Input: Fruit=['A', 'B', 'C', 'A', 'C'] Output: 3
Explanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C'] Example 2:

Input: Fruit=['A', 'B', 'C', 'B', 'B', 'C'] Output: 5
Explanation: We can put 3 'B' in one basket and two 'C' in the other basket.
This can be done if we start with the second letter: ['B', 'C', 'B', 'B', 'C']

和 k个不同字符最长子串是一样的,此时k == 2

  public static int findLength(char[] arr) {
        HashMap<Character, Integer> map = new HashMap<>();
        int sum = 0;
        int start = 0;
        int result = Integer.MIN_VALUE;
        for(int i = 0; i < arr.length; i++){
            if(map.getOrDefault(arr[i], 0) == 0) {
                sum++;
            }
            map.put(arr[i],map.getOrDefault(arr[i], 0) + 1);
            while ( sum > 2){
                map.put(arr[start],map.getOrDefault(arr[start], 0) -1);
                if(map.getOrDefault(arr[start], 0) == 0){
                    sum--;
                }
                start++;
            }
            if (sum == 2) {
                result = Math.max(result, i - start + 1);
            }
        }
        return result != Integer.MIN_VALUE ? result : -1;
  }