-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapacityToShipPackagesWithinDDays.cpp
More file actions
82 lines (66 loc) · 1.59 KB
/
Copy pathcapacityToShipPackagesWithinDDays.cpp
File metadata and controls
82 lines (66 loc) · 1.59 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
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
#include <iostream>
#include <vector>
// 3, 2, 2, 4, 1, 4
// 3 5 7 11 12 16
// 5
// 16
class Solution
{
public:
bool check(std::vector<int>& weights, int capicity ,int days) {
int weightLength = weights.size();
int deleverDays = 0;
int i = 0;
while (i < weightLength)
{
int j = i;
int tempSum = 0;
while (j < weightLength && (tempSum + weights[j]) <= capicity)
{
tempSum += weights[j];
j += 1;
}
deleverDays += 1;
if (deleverDays > days) return false;
i = j;
}
return true;
}
int shipWithinDays(std::vector<int>& weights, int days)
{
int weightLength = weights.size();
if (weightLength == 1) return 1;
int left = 0, right = 0;
/**
* 找出總和的 weight &
* 總和除以 days;
* left -------- right
* */
for (int i = 0; i < weightLength; i++)
{
right += weights[i];
}
left = right / days;
// 答案一定是在這兩者之間
while (left < right)
{
int capacity = left + (right - left) / 2;
if (check(weights, capacity, days))
{ // 可以裝完
right = capacity;
} else
{ // 不夠裝
left = capacity + 1;
}
}
return left;
}
};
int main() {
Solution SolutionInstance;
std::vector<int> weights = { 3, 2, 2, 4, 1, 4 };
int days = 3;
int result = SolutionInstance.shipWithinDays(weights, days);
std::cout << "result is: " << result << std::endl;
return 0;
}