Maximum Candies You Can Get from Boxes LeetCode solution in JavaScript

1
var maxCandies = function (
2
status,
3
candies,
4
keys,
5
containedBoxes,
6
initialBoxes
7
) {
8
var candyCounter = 0;
9
//set is like array, but does not allow duplicates and can have object references
10
var ownedKeys = new Set();
11
var ownedBoxes = initialBoxes;
12
var checkedBoxes = [];
13
for (let i = 0; i < ownedBoxes.length; i++) {
14
let curBox = ownedBoxes[i];
15
//checks if the box being checked is open or you have a key, then adds contents of the box to my data structures
16
//Set.prototype.has is like Array.prototype.includes
17
if (ownedKeys.has(curBox) || status[curBox]) {
18
candyCounter += candies[curBox];
19
//clears checked boxes so keys can be re-referenced
20
checkedBoxes = [];
21
for (let j = 0; j < keys[curBox].length; j++) {
22
//add is like push, but for sets
23
ownedKeys.add(keys[curBox][j]);
24
}
25
for (let j = 0; j < containedBoxes[curBox].length; j++) {
26
ownedBoxes.push(containedBoxes[curBox][j]);
27
}
28
}
29
//Prevents infinite looping by maintaining a ledger of checked boxes, which is cleared upon a successful opening
30
else if (!checkedBoxes.includes(curBox)) {
31
//takes the box being checked and moves it to the end of the array, and marks it as checked
32
ownedBoxes.push(curBox);
33
checkedBoxes.push(curBox);
34
ownedBoxes.splice(i, 1);
35
//de-iterate i to account for the removal of this number at its previous index
36
i--;
37
}
38
}
39
return candyCounter;
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0