-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathCapacity To Ship Packages Within D Days.java
43 lines (41 loc) · 1.34 KB
/
Capacity To Ship Packages Within D Days.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 0;
int right = 0;
// left is the biggest element in the array. It's set as the lower boundary.
// right is the sum of the array, which is the upper limit.
for (int weight : weights) {
left = Math.max(weight, left);
right += weight;
}
int res = 0;
while (left <= right) {
int mid = (left + right) / 2;
// make sure mid is a possible value
if (isPossible(weights, days, mid)) {
res = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return res;
}
public boolean isPossible(int [] weights, int days, int mid) {
int totalDays = 1;
int totalWeight = 0;
for (int i = 0; i < weights.length; i++) {
totalWeight += weights[i];
// increase totalDays if totalWeight is larger than mid
if (totalWeight > mid) {
totalDays++;
totalWeight = weights[i];
}
// the problem states all the packages have to ship within `days` days
if (totalDays > days) {
return false;
}
}
return true;
}
}