题目链接:添加链接描述
二分搜运力:左指针初始化为最大重量(不然最大的那个运不了),右指针初始化为总重量(假设一天全运完)
每次贪心计算当前运力需要的最大天数(因为要求最小运力,所以贪心时直接求最大天数即可),并更新左右指针
代码如下:
class Solution {
public:
int shipWithinDays(vector<int>& weights, int D) {
int left = *max_element(weights.begin(), weights.end());
//accumulate: 从weights.begin() 到 weights.end()求累加和,初始值为0
int right = accumulate(weights.begin(), weights.end(), 0);
int res = INT_MAX;
while(left<=right){
int mid = (left + right) / 2;
int temp = 0, day = 0;
for(int i = 0; i < weights.size(); i++) {
temp += weights[i];
if(temp > mid) {
day++;
temp = weights[i];
}
}
day++;
if(day > D) {
left = mid + 1;
} else {
right = mid - 1;
res = min(res, mid);
}
}
return res;
}
};