A conveyor belt has packages that must be shipped from one port to another within D
days.css
The i
-th package on the conveyor belt has a weight of weights[i]
. Each day, we load the ship with packages on the conveyor belt (in the order given by weights
). We may not load more weight than the maximum weight capacity of the ship.this
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D
days.spa
Example 1:code
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:blog
Input: weights = [3,2,2,4,1,4], D = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4
Example 3:ip
Input: weights = [1,2,3,1,1], D = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1
Note:ci
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
題意:it
weights = [1,2,3,4,5,6,7,8,9,10]
把weights分紅D份,求min{max(每份之和)}。
e.g.
case 1
[1,2,3,|4,5,|6,|7,8,|9,10]
max (6, 9, 6, 15, 19) = 19
case 2 (best case)
[1,2,3,4,5,|6,7,|8,|9,|10]
max(15, 13, 8,9,10) = 15
min{max(每份之和)} = 15
解法: binary search 二分答案,看用該答案是否能夠把weights分紅D份,
若是能夠,說明答案可能大了, 若是不能夠,說明答案小了io
1 public int shipWithinDays(int[] weights, int D) { 2 int sum = 0; 3 int maxWeight = Integer.MIN_VALUE; 4 for (int i = 0; i < weights.length; i++) { 5 sum += weights[i]; 6 maxWeight = Math.max(weights[i], maxWeight); 7 } 8 9 int start = maxWeight; 10 int end = sum; 11 12 while (start + 1 < end) { 13 int mid = start + (end - start) / 2; 14 if (isValid(mid, weights, D)) { 15 end = mid; 16 } else { 17 start = mid; 18 } 19 } 20 if (isValid(start, weights, D)) { 21 return start; 22 } 23 if (isValid(end, weights, D)) { 24 return end; 25 } 26 return -1; 27 } 28 private boolean isValid(int capacity, int[] weights, int D) { 29 int cur = 0; 30 int bag = 0; 31 for (int i = 0; i < weights.length; i++) { 32 if (cur + weights[i] <= capacity) { 33 cur += weights[i]; 34 } else { 35 bag++; 36 cur = weights[i]; 37 } 38 } 39 bag++; 40 if (bag <= D) { 41 return true; 42 } 43 return false; 44 }