Capacity To Ship Packages Within D Days LeetCode solution in JavaScript

1
/**
2
* @param {number[]} weights
3
* @param {number} days
4
* @return {number}
5
*/
6
var shipWithinDays = function (weights, days) {
7
// set left as max of weight, set right as sum of weight
8
let left = Math.max(...weights),
9
right = weights.reduce((a, b) => a + b);
10

11
// max weight cannot exceed the capacity of ship
12
while (left < right) {
13
// set middle weight
14
const m = Math.floor((left + right) / 2);
15
// reset weight if can be load
16
can(m) ? (left = m + 1) : (right = m);
17
}
18

19
// result
20
return left;
21

22
// check if load can be
23
function can(v) {
24
let need = 1,
25
current = 0;
26

27
for (let i of weights) {
28
if (current + i > v) {
29
need++;
30
current = i;
31
} else {
32
current += i;
33
}
34
}
35

36
return need > days;
37
}
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0