-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmaximum-bitwise-and-after-increment-operations.cpp
More file actions
50 lines (48 loc) · 1.67 KB
/
maximum-bitwise-and-after-increment-operations.cpp
File metadata and controls
50 lines (48 loc) · 1.67 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
// Time: O(nlogr)
// Space: O(n)
// bitmasks, greedy, quick select
class Solution {
public:
int maximumAND(vector<int>& nums, int k, int m) {
int result = 0;
for (int i = bit_width(static_cast<uint32_t>(ranges::max(nums) + k)) - 1; i >= 0; --i) {
const auto& target = result | (1 << i);
vector<int> costs;
costs.reserve(size(nums));
for (const auto& x : nums) {
const auto& l = bit_width(static_cast<uint32_t>(target & ~x));
const auto& mask = (1ll << l) - 1;
costs.emplace_back((target & mask) - (x & mask));
}
ranges::nth_element(costs, begin(costs) + (m - 1));
if (accumulate(cbegin(costs), cbegin(costs) + m, 0ll) <= k) {
result |= 1 << i;
}
}
return result;
}
};
// Time: O(nlogn * logr)
// Space: O(n)
// bitmasks, greedy, sort
class Solution2 {
public:
int maximumAND(vector<int>& nums, int k, int m) {
int result = 0;
for (int i = bit_width(static_cast<uint32_t>(ranges::max(nums) + k)) - 1; i >= 0; --i) {
const auto& target = result | (1 << i);
vector<int> costs;
costs.reserve(size(nums));
for (const auto& x : nums) {
const auto& l = bit_width(static_cast<uint32_t>(target & ~x));
const auto& mask = (1ll << l) - 1;
costs.emplace_back((target & mask) - (x & mask));
}
ranges::sort(costs);
if (accumulate(cbegin(costs), cbegin(costs) + m, 0ll) <= k) {
result |= 1 << i;
}
}
return result;
}
};