-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1011.cpp
More file actions
46 lines (36 loc) · 1.02 KB
/
Copy path1011.cpp
File metadata and controls
46 lines (36 loc) · 1.02 KB
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 <numeric>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int left = *max_element(weights.begin(), weights.end());
int right = accumulate(weights.begin(), weights.end(), 0);
int res = right;
while (left <= right) {
int cap = left + (right - left) / 2;
if (canShip(weights, cap, days)) {
res = min(res, cap);
right = cap - 1;
}
else
left = cap + 1;
}
return res;
}
private:
bool canShip(vector<int>& weights, int cap, int days) {
int ships = 1, currCap = cap;
for (int w : weights) {
if (currCap - w < 0) {
ships++;
if (ships > days)
return false;
currCap = cap;
}
currCap -= w;
}
return true;
}
};