-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path1011-capacity-to-ship-packages-within-d-days.cpp
53 lines (40 loc) · 1.2 KB
/
1011-capacity-to-ship-packages-within-d-days.cpp
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
/*
Shipping capacity at the least needs to be
as much as the highest weight on the conveyor
belt and at the maximum can be total of all
the weights on the conveyor belt.
Time Complexity -> O(nlogn)
Space Complexity -> O(1)
*/
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int high = 0;
int low = 0;
for (int i = 0; i < weights.size(); i++) {
high += weights[i];
low = max(low, weights[i]);
}
int answer = high;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canShipWithinDays(weights, days, mid)) {
high = mid - 1;
answer = min(answer, mid);
} else low = mid + 1;
}
return answer;
}
private:
bool canShipWithinDays(vector<int>&weights, int days, int max) {
int sum = 0;
for (int i = 0; i < weights.size() - 1; i++) {
sum += weights[i];
if (sum + weights[i + 1] > max) {
sum = 0;
days--;
}
}
return days > 0;
}
};