-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-number-of-coins-to-be-added.cpp
60 lines (58 loc) · 1.54 KB
/
minimum-number-of-coins-to-be-added.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
// Time: O(nlogn + logt)
// Space: O(1)
// lc0330
// sort, greedy
class Solution {
public:
int minimumAddedCoins(vector<int>& coins, int target) {
sort(begin(coins), end(coins));
int result = 0, reachable = 0;
for (const auto& x : coins) {
// if (x > target) {
// break;
// }
while (!(reachable >= x - 1)) {
++result;
reachable += reachable + 1;
}
if (reachable >= target - x) {
return result;
}
reachable += x;
}
++result;
for (; !(reachable >= target - (reachable + 1)); reachable += reachable + 1) {
++result;
}
return result;
}
};
// Time: O(nlogn + logt)
// Space: O(1)
// lc0330
// sort, greedy
class Solution2 {
public:
int minimumAddedCoins(vector<int>& coins, int target) {
sort(begin(coins), end(coins));
int result = 0, reachable = 0;
for (const auto& x : coins) {
while (!(reachable >= x - 1)) {
++result;
if (reachable >= target - (reachable + 1)) {
return result;
}
reachable += reachable + 1;
}
if (reachable >= target - x) {
return result;
}
reachable += x;
}
++result;
for (; !(reachable >= target - (reachable + 1)); reachable += reachable + 1) {
++result;
}
return result;
}
};