-
Notifications
You must be signed in to change notification settings - Fork 0
/
CapacityToShipPackagesWithinDDays.java
59 lines (55 loc) · 1.65 KB
/
CapacityToShipPackagesWithinDDays.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
package leetcode;
/**
* CapacityToShipPackagesWithinDDays
* https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
* 1011. 在 D 天内送达包裹的能力
* https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/solution/er-fen-sou-suo-by-oshdyr-5igq/
*
* @author tobin
* @since 2021-04-26
*/
public class CapacityToShipPackagesWithinDDays {
public static void main(String[] args) {
CapacityToShipPackagesWithinDDays sol = new CapacityToShipPackagesWithinDDays();
System.out.println(sol.shipWithinDays(new int[]{1, 2, 3, 1, 1}, 4));
System.out.println(sol.shipWithinDays(new int[]{3, 2, 2, 4, 1, 4}, 3));
}
public int shipWithinDays(int[] weights, int D) {
int maxWeight = 0;
int sumWeight = 0;
for (int weight : weights) {
if (weight > maxWeight) {
maxWeight = weight;
}
sumWeight += weight;
}
int left = maxWeight;
int right = sumWeight;
while (left < right) {
int mid = (left + right) / 2;
int times = count(weights, mid);
if (times <= D) {
right = mid;
} else {
left = mid + 1;
}
}
return right;
}
public int count(int[] weights, int max) {
int times = 0;
int sum = 0;
for (int weight : weights) {
if (sum + weight <= max) {
sum += weight;
} else {
times++;
sum = weight;
}
}
if (sum > 0) {
times++;
}
return times;
}
}