Skip to main content

Command Palette

Search for a command to run...

fruit basket

Published
1 min readView as Markdown
import java.util.*;

public class Solution {
    public int totalFruit(int[] fruits) {
        if (fruits == null || fruits.length == 0) return 0;

        Map<Integer, Integer> count = new HashMap<>();
        int left = 0, maxFruits = 0;

        for (int right = 0; right < fruits.length; right++) {
            count.put(fruits[right], count.getOrDefault(fruits[right], 0) + 1);

            // If more than 2 distinct fruit types, shrink window from the left
            while (count.size() > 2) {
                int leftFruit = fruits[left];
                count.put(leftFruit, count.get(leftFruit) - 1);
                if (count.get(leftFruit) == 0) {
                    count.remove(leftFruit);
                }
                left++;
            }

            // Update maximum
            maxFruits = Math.max(maxFruits, right - left + 1);
        }

        return maxFruits;
    }

    // Example usage
    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] fruits = {1, 2, 1};  // expected output: 3
        System.out.println(sol.totalFruit(fruits));
    }
}

More from this blog

Amit singh's blog

235 posts