class Solution {
// // 二分查找左侧边界模板
public int shipWithinDays(int[] weights, int D) {
// 载重可能的最小值
int left = getMax(weights);
// 载重可能的最大值
int right = getSum(weights);
while (left <= right) {
int mid = left + (right - left) / 2;
if (canFinishAll(weights, D, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
// 辅助函数,船最大载重为 capacity,是否能在 D 天内运完货物?
boolean canFinishAll(int[] weights, int D, int capacity) {
// 当前运输货物对应下标
int i = 0;
for (int day = 0; day < D; day++) {
// 开辟新的空间存储载重
int maxCapacity = capacity;
while ((maxCapacity -= weights[i]) >= 0) {
// 下一件运输货物对应下标
i++;
// 最后一件货物 i-1 已运输完毕
if (i == weights.length)
return true;
}
}
return false;
}
// 求数组中最大值
int getMax(int[] weights) {
int max = 0;
for (int weight : weights)
max = Math.max(weight, max);
return max;
}
// 数组求和
int getSum(int[] weights) {
int sum = 0;
for (int weight : weights)
sum += weight;
return sum;
}
}