-
Notifications
You must be signed in to change notification settings - Fork 0
/
KthSmallestAmountWithSingleDenominationCombination.cpp
46 lines (40 loc) · 1.3 KB
/
KthSmallestAmountWithSingleDenominationCombination.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
class Solution {
public:
long long findKthSmallest(vector<int>& coins, int k) {
int max_coin = 0;
for (int i = 0; i < coins.size(); i++) {
max_coin = max(max_coin, coins[i]);
}
long long* LCMs = new long long[1 << coins.size()];
for (unsigned int i = 1; i < 1 << coins.size(); i++) {
LCMs[i] = 1;
for (int j = 0; j < coins.size(); j++) {
if (i & (1 << j)) { // the j'th bit of i
LCMs[i] = lcm(LCMs[i], coins[j]);
}
}
}
// binary search
long long left = 0, right = (long long)max_coin * k;
while (left < right) {
long long mid = left + (right - left) / 2;
long long count = 0;
for (unsigned int i = 1; i < 1 << coins.size(); i++) {
if (popcount(i) % 2) {
count += mid / LCMs[i];
} else {
count -= mid / LCMs[i];
}
}
if (count == k) { // count <= mid < count+1
right = mid;
} else if (count < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// left == right == k, 1 element
return left;
}
};