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.
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, right = max(weights), sum(weights)
13 while left < right:
14 mid = left + (right - left) // 2
15 if self.canShip(weights, days, mid):
16 right = mid
17 else:
18 left = mid + 1
19 return left
20
21# Example usage
22solution = Solution()
23weights = [1,2,3,4,5,6,7,8,9,10]
24days = 5
25print(solution.shipWithinDays(weights,days)) # Output: 15
The Python solution defines a canShip
method to determine the feasibility of shipping with a given capacity. The main shipWithinDays
function applies binary search to find the minimum capacity required. The process iterates until the ideal capacity is found.
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).
1using System;
2using System.Linq;
3
4class Solution {
5 public bool CanShip(int[] weights, int days, int capacity) {
6 int total = 0, dayCount = 1;
7 foreach (int weight in weights) {
8 if (total + weight > capacity) {
9 dayCount++;
10 total = 0;
11 }
12 total += weight;
13 }
14 return dayCount <= days;
15 }
16
17 public int ShipWithinDays(int[] weights, int days) {
18 int left = weights.Max();
19 while (!CanShip(weights, days, left))
20 left++;
21 return left;
22 }
23
24 static void Main() {
25 Solution solution = new Solution();
26 int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
27 int days = 5;
28 Console.WriteLine(solution.ShipWithinDays(weights, days)); // Output: 15
29 }
30}
This C# solution also starts at the maximum weight and increments capacity until a feasible solution is found. It employs the CanShip
function to test capacity validity iteratively.