Untitled
import java.util.HashMap; import java.util.Map; public class FruitCollector { public int totalFruit(int[] fruits) { Map<Integer, Integer> map = new HashMap<>(); int i = 0, j = 0, maxFruits = 0; while (j < fruits.length) { // Add the current fruit to the map map.put(fruits[j], map.getOrDefault(fruits[j], 0) + 1); // Shrink once , u can also write for generic k if (map.size() > 2) { int fruitAtI = fruits[i]; map.put(fruitAtI, map.get(fruitAtI) - 1); if (map.get(fruitAtI) == 0) { map.remove(fruitAtI); } i++; // Shrink the window } /// this check is needed for single shrink approach if(map.size()<=2) maxFruits = Math.max(maxFruits, j - i + 1); // Move the right pointer j++; } return maxFruits; } }
Leave a Comment