-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path1011.java
More file actions
73 lines (72 loc) · 2.06 KB
/
1011.java
File metadata and controls
73 lines (72 loc) · 2.06 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
__________________________________________________________________________________________________
sample 4 ms submission
class Solution {
private boolean isPossible(int[] weights, int capacity, int D) {
int count = 0;
int sum = 0;
for (int i = 0; i < weights.length; i++) {
if (weights[i] > capacity) {
return false;
}
if (sum + weights[i] > capacity) {
count++;
sum = 0;
}
sum += weights[i];
}
count++;
if (count > D) {
return false;
}
return true;
}
public int shipWithinDays(int[] weights, int D) {
int sum = 0;
int low = 1;
int high = (weights.length * 500) / D;
int minPossible = high;
while (low <= high) {
int mid = (low + high) / 2;
if (isPossible(weights, mid, D)) {
minPossible = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return minPossible;
}
}
__________________________________________________________________________________________________
sample 40508 kb submission
class Solution {
public int shipWithinDays(int[] weights, int D) {
if (weights == null || weights.length == 0) return 0;
int right = Arrays.stream(weights).sum();
int left = Arrays.stream(weights).max().getAsInt();
while (left < right) {
int mid = left + (right - left) / 2;
if (canDivid(weights, mid, D)) {
right = mid;
} else {
left = mid + 1;
}
}
System.out.println("capacity " + left);
return left;
}
private boolean canDivid(int[] weights, int capacity, int D) {
int count = 1;
int sum = 0;
for (int w : weights) {
if (sum + w > capacity) {
sum = 0;
count++;
}
sum += w;
if (count > D) return false;
}
return true;
}
}
__________________________________________________________________________________________________