-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1011.js
38 lines (27 loc) · 840 Bytes
/
1011.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @param {number[]} weights
* @param {number} days
* @return {number}
*/
var shipWithinDays = function (weights, days) {
const findRequiredDays = (capacity) => {
let numOfDays = 1;
let loaded = 0;
for (let weight of weights) {
if (loaded + weight > capacity) {
loaded = weight;
numOfDays++;
} else loaded += weight;
}
return numOfDays;
};
let left = Math.max(...weights);
let right = weights.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const requiredDays = findRequiredDays(mid);
if (requiredDays <= days) right = mid - 1;
else left = mid + 1;
}
return left;
};