Maximum Bags With Full Capacity of Rocks LeetCode solution in JavaScript

1
var maximumBags = function (capacity, rocks, additionalRocks) {
2
var differences = [];
3
var count = 0;
4
for (let i in rocks) {
5
if (capacity[i] - rocks[i] > 0) {
6
// check if rocks[i] is less than capacity[i]
7
differences.push(capacity[i] - rocks[i]); // add the difference
8
} else {
9
count++; // rocks[i] is at full capacity, so the result goes up by 1
10
}
11
}
12
differences.sort((a, b) => a - b); // sort the differences
13
var r = additionalRocks;
14
while (r != 0 && differences.length > 0) {
15
// loop through differences until there is no more rocks or all of the bags of rocks are at full capacity
16
if (differences[0] <= r) {
17
r -= differences[0]; // minus the difference of the rocks
18
count++; // add to result because another bag of rocks is at full capacity
19
} else {
20
break; // rocks can not make any other bags at full capacity, so stop right here
21
}
22
differences.shift(); // remove the first difference
23
}
24
return count;
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0