-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcapacity_to_ship_within_d_days.cpp
46 lines (36 loc) · 1.3 KB
/
capacity_to_ship_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
class Solution {
bool isPossibleAllocation(int barrier, vector<int> &weights, int &totalDays, int &totalWeights) {
//totalWeights = number of weights
int allowedDays = 1, capacity = 0;
for(auto weight : weights) {
if(weight > barrier) return false;
if(weight + capacity > barrier) {
allowedDays++; //reallocate capacity
capacity = weight;
// if(allowedDays > totalDays) return false;
}
else
capacity += weight;
}
return (allowedDays <= totalDays) ? true : false;
}
public:
int shipWithinDays(vector<int>& weights, int days) {
int totalWeights = weights.size(), totalDays = days;
int res = -1;
int left = weights[totalWeights - 1], right = accumulate(weights.begin(), weights.end(), 0);
while(left < right) {
//find mid
int mid = left + (right - left) / 2;
//condition
if(isPossibleAllocation(mid, weights, totalDays, totalWeights)) {
right = mid;
}
//else
else {
left = mid + 1;
}
}
return left;
}
};