-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1011.cpp
More file actions
29 lines (29 loc) · 850 Bytes
/
1011.cpp
File metadata and controls
29 lines (29 loc) · 850 Bytes
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
class Solution
{
public:
int shipWithinDays(vector<int>& weights, int D)
{
// 确定二分查找左右边界
int left = *max_element(weights.begin(), weights.end()), right = accumulate(weights.begin(), weights.end(), 0);
while (left < right) {
int mid = (left + right) / 2;
// need 为需要运送的天数
// cur 为当前这一天已经运送的包裹重量之和
int need = 1, cur = 0;
for (int weight: weights) {
if (cur + weight > mid) {
++need;
cur = 0;
}
cur += weight;
}
if (need <= D) {
right = mid;
}
else {
left = mid + 1;
}
}
return left;
}
};