传送带上的包裹必须在 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) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], D = 3
输出:6
解释:
船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
第 1 天:3, 2
第 2 天:2, 4
第 3 天:1, 4
示例 3:
输入:weights = [1,2,3,1,1], D = 4
输出:3
解释:
第 1 天:1
第 2 天:2
第 3 天:3
第 4 天:1, 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int shipWithinDays(int[] weights, int D) {
if (weights == null || weights.length == 0) return 0;
// return shipWithinDaysI(weights, D);
return shipWithinDaysII(weights, D);
}
//方法二:二分搜索
//在方法一中可以发现运载能力carry是线性增长的,可以使用二分查找法
//时间复杂度O(NlogN),空间复杂度O(1)
private int shipWithinDaysII(int[] weights, int d) {
int left = 0, right = 1;
for (int weight : weights) {
left = Math.max(left, weight);
right += weight;
}
while (left < right) {
int mid = left + (right - left) / 2;
if (canFinish(weights, d, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
//方法一:暴力解法
//假设最低运载能力为carry,carry最小值为max(weights),最大值为sum(weights)
//遍历数组,直到找到能在D天内完成的运载能力
//时间复杂度O(n^2),空间复杂度O(1)
private int shipWithinDaysI(int[] weights, int d) {
int minCarry = 0, maxCarry = 0;
for (int weight : weights) {
minCarry = Math.max(minCarry, weight);
maxCarry += weight;
}
for (int carry = minCarry; carry <= maxCarry; carry++) {
if (canFinish(weights, d, carry)) {
return carry;
}
}
return maxCarry;
}
private boolean canFinish(int[] weights, int D, int carry) {
int count = 1;
int current = 0;
for (int weight : weights) {
if (current + weight > carry) {
count += 1;
current = 0;
}
current += weight;
}
return count <= D;
}
}