Capacity To Ship Packages Within D Days
Time complexity: $O(n\log M)$
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
|
#include <iostream>
#include <vector>
class Solution {
public:
int shipWithinDays(std::vector<int>& weights, int days) {
int left = 0, right = 0;
for (int w : weights) {
left = std::max(left, w);
right += w;
}
if (days >= weights.size()) {
return left;
}
for (int mid = (left + right) / 2; right > left;) {
if (check(weights, days, mid)) {
right = mid;
}
else {
left = mid + 1;
}
mid = (left + right) / 2;
}
return left;
}
private:
bool check(std::vector<int>& weights, int days, int cap) {
int cur = 0;
for (int weight : weights) {
cur += weight;
if (cur > cap) {
cur = weight;
if (!(--days)) {
return false;
}
}
}
return true;
}
};
|
