Skip to content

Commit b84dfe4

Browse files
authored
Create capacity-to-ship-packages-within-d-days.cpp
1 parent 23221ea commit b84dfe4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(nlogr)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int shipWithinDays(vector<int>& weights, int D) {
7+
int left = *max_element(weights.cbegin(), weights.cend());
8+
int right = accumulate(weights.cbegin(), weights.cend(), 0);
9+
while (left <= right) {
10+
int mid = left + (right - left) / 2;
11+
if (possible(weights, D, mid)) {
12+
right = mid - 1;
13+
} else {
14+
left = mid + 1;
15+
}
16+
}
17+
return left;
18+
}
19+
20+
private:
21+
int possible(const vector<int>& weights, int D, int mid) const {
22+
int result = 1, curr = 0;
23+
for (const auto& w : weights) {
24+
if (curr + w > mid) {
25+
++result;
26+
curr = 0;
27+
}
28+
curr += w;
29+
}
30+
return result <= D;
31+
}
32+
};

0 commit comments

Comments
 (0)