Skip to content

Commit 0d25362

Browse files
committed
8ms, 95%, 60%. binary search.
1 parent 3d99668 commit 0d25362

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* @lc app=leetcode id=1011 lang=java
3+
*
4+
* [1011] Capacity To Ship Packages Within D Days
5+
*/
6+
7+
// @lc code=start
8+
9+
/**
10+
* Explanation
11+
* Given the number of bags,
12+
* return the minimum capacity of each bag,
13+
* so that we can put items one by one into all bags.
14+
*
15+
* We binary search the final result.
16+
* The left bound is max(A), The right bound is sum(A).
17+
*/
18+
class Solution {
19+
public int shipWithinDays(int[] weights, int D) {
20+
int left = 0, right = 0;
21+
for (int w : weights) {
22+
left = Math.max(left, w);
23+
right += w;
24+
}
25+
while (left < right) {
26+
int mid = (left + right) / 2;
27+
if (getNeed(weights, mid) > D)
28+
left = mid + 1;
29+
else
30+
right = mid;
31+
}
32+
return left;
33+
}
34+
35+
public int getNeed(int[] weights, int mid) {
36+
int need = 1, cur = 0;
37+
for (int w : weights) {
38+
if (cur + w > mid) {
39+
need += 1;
40+
cur = 0;
41+
}
42+
cur += w;
43+
}
44+
45+
return need;
46+
}
47+
}
48+
// @lc code=end

0 commit comments

Comments
 (0)