leetcode-1011 在 D 天内送达包裹的能力

题目描述:传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。

传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。

返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public int shipWithinDays(int[] weights, int days) {
int minWeight = Integer.MIN_VALUE;
int maxWeight = 0;
int len = weights.length;
for (int i = 0; i < len; i++) {
maxWeight += weights[i];
if (weights[i] > minWeight) {
minWeight = weights[i];
}
}
int left = minWeight;
int right = maxWeight;
while (left <= right) {
int mid = left + (right - left) / 2;
int currentDays = calculateDays(weights, mid);
if (currentDays == days) {
right = mid - 1;
} else if (currentDays < days) {
right = mid - 1;
} else if (currentDays > days) {
left = mid + 1;
}
}
return left;
}

public int calculateDays(int[] weights, int weight) {
int days = 0;
int i = 0;
int tmpWeight = weight;
while (i < weights.length) {
if (tmpWeight >= weights[i]) {
tmpWeight -= weights[i];
i++;
if (i == weights.length) {
days++;
}
} else {
tmpWeight = weight;
days++;
}
}
return days;
}
}