-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCapacityToShipPackagesWithinDDays.cpp
More file actions
39 lines (38 loc) · 1 KB
/
CapacityToShipPackagesWithinDDays.cpp
File metadata and controls
39 lines (38 loc) · 1 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
#include <iostream>
#include <vector>
class Solution {
public:
int shipWithinDays(std::vector<int>& weights, int days) {
int cur = 0;
for(int i = 0; i < weights.size(); i++) {
cur += weights[i];
}
int max = cur;
while(true) {
if(canShip(weights,days,cur)) {
if(!canShip(weights,days,cur-1)) break;
max = cur;
cur = cur/2;
}
else {
cur = (max+cur)/2;
}
}
return cur;
}
bool canShip(std::vector<int>&weights, int days, int cap) {
int temp = cap;
for(int i = 0; i < weights.size(); i++) {
temp -= weights[i];
if(temp <= 0) {
days--;
temp == 0 ? NULL : i--;
if(days == 0 && !(i == weights.size()-1 && temp == 0)) {
return false;
}
temp = cap;
}
}
return true;
}
};