-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCapacity_1014.java
More file actions
30 lines (29 loc) · 803 Bytes
/
Capacity_1014.java
File metadata and controls
30 lines (29 loc) · 803 Bytes
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
class Capacity_1014 {
// My first solution (similar with most voted)
public int shipWithinDays(int[] weights, int D) {
int max = 0;
for (int w : weights) max = Math.max(max, w);
int l = max, r = Integer.MAX_VALUE;
while (l < r) {
int mid = l + (r - l) / 2;
if (daysNeed(weights, mid) > D)
l = mid + 1;
else
r = mid;
}
return r;
}
private int daysNeed(int[] weights, int capacity) {
int days = 0;
int remain = capacity;
for (int w : weights) {
if (w > remain) {
days++;
remain = capacity - w;
} else {
remain -= w;
}
}
return days + 1;
}
}