-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCapacityToShipPackagesWithinDDays.cpp
46 lines (46 loc) · 1.3 KB
/
CapacityToShipPackagesWithinDDays.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
//Approach 1: using binary search checking different weight value within the
//required range
//Time : O(N log N)
class Solution {
public:
bool check(vector<int> w , long long int cap, int D){
int days = 1;
int i = 0;
for(i = 0; i<w.size();){
long long int curr_sum= 0;
while(i<w.size() && curr_sum + w[i] <=cap){
curr_sum += w[i];
i++;
}
curr_sum = 0;
if(days >D){
return false;
}
days++;
}
return true;
}
int shipWithinDays(vector<int>& w, int D) {
if(D == w.size()){
return *max_element(w.begin(), w.end());
}
if( D == 1){
return accumulate(w.begin(), w.end(), 0);
}
long long int total = accumulate(w.begin(), w.end(), 0);
long long int maxVal = *max_element(w.begin(), w.end());
long long int low = maxVal;
long long int high = total;
long long int res = INT_MAX;
while(low <= high){
long long int mid = low + (high - low)/2;
if(check(w, mid, D)){
high = mid-1;
res = min(res, mid);
}else{
low = mid +1;
}
}
return res;
}
};