forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1011.java
57 lines (46 loc) · 1.51 KB
/
_1011.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.fishercoder.solutions;
public class _1011 {
public static class Solution1 {
public int daysToShip(int[] weights, int capacity) {
int days = 0;
int currentShip = 0;
for (int k : weights) {
if (currentShip + k > capacity) {
currentShip = 0;
days += 1;
}
currentShip += k;
}
return days + 1;
}
public int shipWithinDays(int[] weights, int D) {
int sum = 0;
int max = 0;
for (int k : weights) {
sum += k;
max = Math.max(max, k);
}
// Minimum possible capacity needs to be as much as the heaviest package
int lower = max;
// Maximum possible capacity is the total weight of all packages
int upper = sum;
if (daysToShip(weights, lower) <= D) {
return lower;
}
// Guess is for capacity
int currentGuess;
int bestGuess = -1;
// Binary search
while (lower <= upper) {
currentGuess = (upper + lower) / 2;
if (daysToShip(weights, currentGuess) <= D) {
bestGuess = currentGuess;
upper = currentGuess - 1;
} else {
lower = currentGuess + 1;
}
}
return bestGuess;
}
}
}