This approach utilizes a binary search to find the minimal ship capacity that can carry all packages within the specified number of days. The binary search operates over the range from the maximum value in the weights array to the sum of all weights, which are the logical lower and upper bounds for the ship capacity.
Time Complexity: O(n log m), where n is the number of packages and m is the range of the binary search (sum of weights - max weight).
Space Complexity: O(1), as we use constant extra space.
1function canShip(weights, days, capacity) {
2 let total = 0, dayCount = 1;
3 for (let weight of weights) {
4 if (total + weight > capacity) {
5 dayCount++;
6 total = 0;
7 }
8 total += weight;
9 }
10 return dayCount <= days;
11}
12
13function shipWithinDays(weights, days) {
14 let left = Math.max(...weights);
15 let right = weights.reduce((acc, val) => acc + val, 0);
16 while (left < right) {
17 let mid = Math.floor(left + (right - left) / 2);
18 if (canShip(weights, days, mid)) {
19 right = mid;
20 } else {
21 left = mid + 1;
22 }
23 }
24 return left;
25}
26
27const weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5;
28console.log(shipWithinDays(weights, days)); // Output: 15
This JavaScript solution implements the binary search process similarly to other languages. We determine bounds with Math.max
and reduce
and adjust them while checking capacities using a helper function. The goal is to find the minimal feasible capacity through repeated bounding of the search space.
This approach involves greedy simulation to estimate the minimum capacity by incrementing from the largest single package weight until you find a capacity that can ship all the packages within the days. Note that this approach may take more time in the worst case due to the linear increment.
Time Complexity: O(n * C/m), where C/m is the number of increments in the worst case.
Space Complexity: O(1).
1class Solution:
2 def canShip(self, weights, days, capacity):
3 total, day_count = 0, 1
4 for weight in weights:
5 if total + weight > capacity:
6 day_count += 1
7 total = 0
8 total += weight
9 return day_count <= days
10
11 def shipWithinDays(self, weights, days):
12 left = max(weights)
13 while not self.canShip(weights, days, left):
14 left += 1
15 return left
16
17# Example usage
18solution = Solution()
19weights = [1,2,3,4,5,6,7,8,9,10]
20days = 5
21print(solution.shipWithinDays(weights, days)) # Output: 15
The Python solution uses a loop to incrementally increase the shipping capacity from the maximum weight until a feasible capacity is found that meets the constraint. The method canShip
evaluates each capacity.