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.
1import java.util.*;
2
3class Solution {
4 public boolean canShip(int[] weights, int days, int capacity) {
5 int total = 0, dayCount = 1;
6 for (int weight : weights) {
7 if (total + weight > capacity) {
8 dayCount++;
9 total = 0;
10 }
11 total += weight;
12 }
13 return dayCount <= days;
14 }
15
16 public int shipWithinDays(int[] weights, int days) {
17 int left = Arrays.stream(weights).max().getAsInt();
18 int right = Arrays.stream(weights).sum();
19 while (left < right) {
20 int mid = left + (right - left) / 2;
21 if (canShip(weights, days, mid)) {
22 right = mid;
23 } else {
24 left = mid + 1;
25 }
26 }
27 return left;
28 }
29
30 public static void main(String[] args) {
31 Solution sol = new Solution();
32 int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
33 int days = 5;
34 System.out.println(sol.shipWithinDays(weights, days)); // Output: 15
35 }
36}
The Java solution uses streams to compute the initial bounds for the binary search. The logic follows the binary search pattern, updating the search space based on whether a mid-point capacity is sufficient or not. The canShip
method checks if a given ship capacity can handle the load within the given days.
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).
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 while (!canShip(weights, days, left)) {
16 left++;
17 }
18 return left;
19}
20
21const weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5;
22console.log(shipWithinDays(weights, days)); // Output: 15
This JavaScript solution employs a simple incrementing loop to find the minimal feasible capacity from the maximum weight of the packages. It uses canShip
to verify efficiency per iteration.