Fruit Into Baskets LeetCode solution in JavaScript

1
var totalFruit = function (fruits) {
2
let myFruits = {};
3
let n = fruits.length;
4
let windowStart = 0;
5
let ans = -Number.MAX_VALUE;
6

7
for (let windowEnd = 0; windowEnd < n; windowEnd++) {
8
let fruit = fruits[windowEnd];
9

10
if (fruit in myFruits) {
11
myFruits[fruit]++;
12
} else {
13
myFruits[fruit] = 1;
14
}
15

16
while (Object.keys(myFruits).length > 2) {
17
let throwOut = fruits[windowStart];
18
myFruits[throwOut]--;
19
if (myFruits[throwOut] == 0) {
20
delete myFruits[throwOut];
21
}
22
windowStart++;
23
}
24
ans = Math.max(ans, windowEnd - windowStart + 1);
25
}
26
return ans;
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0