传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
思路:
根据题意:装船的最低装载能力记为D,D的最小值不能小于数组中的最大值(因为货物不可拆分),D的最大值不会超过货物的总重
二分法:
代码
class Solution {
public int shipWithinDays(int[] weights, int D) {
int min = weights[0];//一次运送的最小负载,即weights中最大值
int sum = 0;//一次运送的最大负载
for(int weight : weights){
sum += weight;
if(min < weight){
min = weight;
}
}
int left = min;//左边界
int right = sum;//右边界
while(left<right){
int mid = (left+right)/2;
int need =1; // 需要的天数
int cur = 0; // 当前负载
for(int weight:weights){
if(weight+cur>mid){
need++;
cur = 0;
}
cur += weight;
}
if(need <= D) {
right = mid;
}else{
left = mid+1;
}
}
return left;
}
}