-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path1011-capacity-to-ship-packages-within-d-days.js
47 lines (42 loc) · 1.28 KB
/
1011-capacity-to-ship-packages-within-d-days.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
39
40
41
42
43
44
45
46
47
/**
* 1011. Capacity To Ship Packages Within D Days
* https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
* Difficulty: Medium
*
* A conveyor belt has packages that must be shipped from one port to another within days days.
*
* The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship
* with packages on the conveyor belt (in the order given by weights). We may not load more weight
* than the maximum weight capacity of the ship.
*
* Return the least weight capacity of the ship that will result in all the packages on the conveyor
* belt being shipped within days days.
*/
/**
* @param {number[]} weights
* @param {number} days
* @return {number}
*/
var shipWithinDays = function(weights, days) {
let left = Math.max(...weights);
let right = weights.reduce((sum, weight) => sum + weight, 0);
while (left < right) {
const mid = Math.floor((left + right) / 2);
let currentDays = 1;
let currentWeight = 0;
for (const weight of weights) {
if (currentWeight + weight > mid) {
currentDays++;
currentWeight = weight;
} else {
currentWeight += weight;
}
}
if (currentDays > days) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
};