1011. Capacity To Ship Packages Within D Days
A conveyor belt has packages that must be shipped from one port to another within D
days.
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.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D
days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5Output: 15Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:1st day: 1, 2, 3, 4, 52nd day: 6, 73rd day: 84th day: 95th day: 10Note 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:
Input: weights = [3,2,2,4,1,4], D = 3Output: 6Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:1st day: 3, 22nd day: 2, 43rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], D = 4Output: 3Explanation: 1st day: 12nd day: 23rd day: 34th day: 1, 1
Note:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
题意:
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份, 如果可以,说明答案可能大了, 如果不可以,说明答案小了
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 }