Untitled
unknown
plain_text
a year ago
986 B
6
Indexable
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 the window until there are at most 2 types of fruits
while (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
}
// Update the maximum number of fruits
maxFruits = Math.max(maxFruits, j - i + 1);
// Move the right pointer
j++;
}
return maxFruits;
}
}
Editor is loading...
Leave a Comment