[LeetCode] Capacity To Ship Packages Within D Days

1011. Capacity To Ship Packages Within D Days

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.

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
class Solution {
int helper(vector<int>& w, int c) {
int d = 1, handle = 0;
for(auto& n : w) {
handle += n;
if(handle > c) {
d++;
handle = n;
}
}
return d;
}
public:
int shipWithinDays(vector<int>& w, int days) {
int l = *max_element(w.begin(), w.end()), r = accumulate(w.begin(),w.end(),0), res = INT_MAX;
while(l <= r) {
int m = l + (r-l) / 2;
if(helper(w,m) <= days) {
res = min(res,m);
r = m - 1;
} else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/capacity-to-ship-packages-within-d-days/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.