-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-possible-number-by-binary-concatenation.cpp
59 lines (55 loc) · 1.53 KB
/
maximum-possible-number-by-binary-concatenation.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
// Time: O(n * logr * logn)
// Space: O(nlogr)
// sort
class Solution {
public:
int maxGoodNumber(vector<int>& nums) {
const auto& to_binary = [](int x) {
string result;
for (; x; x >>= 1) {
result.push_back(x & 1 ? '1' : '0');
}
reverse(begin(result), end(result));
return result;
};
vector<string> bins(size(nums));
for (int i = 0; i < size(nums); ++i) {
bins[i] = to_binary(nums[i]);
}
sort(begin(bins), end(bins), [](const auto& a, const auto& b) {
return (a + b) > (b + a);
});
string result;
for (const auto& x : bins) {
result += x;
}
return stoi(result, nullptr, 2);
}
};
// Time: O(n! * nlogr)
// Space: O(nlogr)
// brute force
class Solution2 {
public:
int maxGoodNumber(vector<int>& nums) {
const auto& to_binary = [](int x) {
string result;
for (; x; x >>= 1) {
result.push_back(x & 1 ? '1' : '0');
}
reverse(begin(result), end(result));
return result;
};
vector<int> idxs(size(nums));
iota(begin(idxs), end(idxs), 0);
int result = 0;
do {
string curr;
for (const auto& i : idxs) {
curr += to_binary(nums[i]);
}
result = max(result, stoi(curr, nullptr, 2));
} while (next_permutation(begin(idxs), end(idxs)));
return result;
}
};