904. Fruit Into Baskets
202410042250
tags: #sliding-window
var totalFruit = function(fruits) {
const map = new Map();
let start = 0;
let res = 0;
for (let end = 0; end < fruits.length; end++) {
const fruit = fruits[end];
map.set(fruit, (map.get(fruit) ?? 0) + 1);
while (map.size > 2) {
const startFruit = fruits[start];
map.set(startFruit, map.get(startFruit) - 1);
if (map.get(startFruit) === 0) {
map.delete(startFruit);
}
start += 1;
}
res = Math.max(res, end - start + 1);
}
return res;
};