-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathL5MaxPairCpp
61 lines (59 loc) · 1.33 KB
/
L5MaxPairCpp
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
struct Node {
Node *links[2];
bool containsKey(int ind) {
return (links[ind] != NULL);
}
Node* get(int ind) {
return links[ind];
}
void put(int ind, Node* node) {
links[ind] = node;
}
};
class Trie {
private: Node* root;
public:
Trie() {
root = new Node();
}
public:
void insert(int num) {
Node* node = root;
// cout << num << endl;
for(int i = 31;i>=0;i--) {
int bit = (num >> i) & 1;
if(!node->containsKey(bit)) {
node->put(bit, new Node());
}
node = node->get(bit);
}
}
public:
int findMax(int num) {
Node* node = root;
int maxNum = 0;
for(int i = 31;i>=0;i--) {
int bit = (num >> i) & 1;
if(node->containsKey(!bit)) {
maxNum = maxNum | (1<<i);
node = node->get(!bit);
}
else {
node = node->get(bit);
}
}
return maxNum;
}
};
int maxXOR(int n, int m, vector<int> &arr1, vector<int> &arr2)
{
Trie trie;
for(int i = 0;i<n;i++) {
trie.insert(arr1[i]);
}
int maxi = 0;
for(int i = 0;i<m;i++) {
maxi = max(maxi, trie.findMax(arr2[i]));
}
return maxi;
}