package com.heu.wsq.leetcode.binarysearch;
/**
* 1011. 在 D 天内送达包裹的能力
* @author wsq
* @date 2021/4/26
* 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
* 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
* 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
*
* 示例 1:
* 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
* 输出:15
* 解释:
* 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
* 第 1 天:1, 2, 3, 4, 5
* 第 2 天:6, 7
* 第 3 天:8
* 第 4 天:9
* 第 5 天:10
*
* 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
*
* 链接:https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
*/
public class ShipWithinDays {
/**
* 这道题跟爱吃香蕉的珂珂的是类似的,找到答案所有的可能性,暴力解法就是从小到大遍历所有可能的可能性,
* 遇到满足条件的就是答案,但是这样做的时间复杂度就是o(N)的
*
* 这样的题就是二分查找的场景,分析场景,得到搜索可能性的范围,范围应该是从小到大有序的,这时候,我们就可以使用二分查找去解决它
* @param weights
* @param D
* @return
*/
public int shipWithinDays(int[] weights, int D) {
if(weights == null || weights.length == 0){
return 0;
}
// 所有包裹的总重量作为搜索范围的最大值,如果也就是说如果ans 为totalWeight的话, 只需要一天就完成搬运
int totalWeight = 0;
// 由于包裹是不可拆分的,所以,我们搜索范围的最小值就是要大于等于单个包裹的最大值
int maxWeight = 0;
for(int w : weights){
totalWeight += w;
if(w > maxWeight){
maxWeight = w;
}
}
int left = maxWeight;
int right = totalWeight;
while(left <= right){
int mid = (left + right) >> 1;
if(canFinsh(weights, mid, D)){
right = mid - 1;
}else{
left = mid + 1;
}
}
return left;
}
private boolean canFinsh(int[] weights, int totalW, int D){
int tmp = 0;
for(int w: weights){
int t = tmp + w;
if(t > totalW){
D--;
tmp = w;
}else{
tmp = t;
}
}
if(tmp > 0){
D--;
}
return D >= 0;
}
}