-
Notifications
You must be signed in to change notification settings - Fork 118
/
1011. Capacity To Ship Packages Within D Days.cpp
98 lines (82 loc) · 2.91 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Runtime: 52 ms, faster than 67.73% of C++ online submissions for Capacity To Ship Packages Within D Days.
//Memory Usage: 12.3 MB, less than 11.11% of C++ online submissions for Capacity To Ship Packages Within D Days.
class Solution {
public:
vector<int> weights;
int D;
bool possible(int C){
int days = 0;
int i = 0; //next day starts from here
while(i < weights.size()){
int cap = 0;
while(i < weights.size() && cap + weights[i] <= C){
cap += weights[i++];
}
days++;
}
return days <= D;
};
int shipWithinDays(vector<int>& weights, int D) {
this->weights = weights;
this->D = D;
//the capcacity must >= max weight of a goods
int l = *max_element(weights.begin(), weights.end());
//we can ship in 1 day
int r = accumulate(weights.begin(), weights.end(), 0);
int mid;
while(l <= r){
mid = (l + r)/2;
// cout << l << " " << mid << " " << r << " " << possible(mid) << endl;
if(possible(mid)){
if(mid == l) return mid;
r = mid;
}else{
//mid is not valid, increase the lower bound
l = mid+1;
}
}
return mid;
}
};
//some modification from
//https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/256729/JavaC%2B%2BPython-Binary-Search
//Runtime: 52 ms, faster than 67.73% of C++ online submissions for Capacity To Ship Packages Within D Days.
//Memory Usage: 12.3 MB, less than 11.11% of C++ online submissions for Capacity To Ship Packages Within D Days.
class Solution {
public:
vector<int> weights;
int D;
bool possible(int C){
int days = 0;
int i = 0; //next day starts from here
while(i < weights.size()){
int cap = 0;
while(i < weights.size() && cap + weights[i] <= C){
cap += weights[i++];
}
days++;
}
return days <= D;
};
int shipWithinDays(vector<int>& weights, int D) {
this->weights = weights;
this->D = D;
//the capcacity must >= max weight of a goods
int l = *max_element(weights.begin(), weights.end());
//we can ship in 1 day
int r = accumulate(weights.begin(), weights.end(), 0);
int mid;
while(l < r){
mid = (l + r)/2;
// cout << l << " " << mid << " " << r << " " << possible(mid) << endl;
if(possible(mid)){
r = mid;
}else{
//mid is not valid, increase the lower bound
l = mid+1;
}
}
//the loop ends at l == r, so now l is the only valid value
return l;
}
};