-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindMaximumXOR.cpp
More file actions
94 lines (79 loc) · 1.9 KB
/
findMaximumXOR.cpp
File metadata and controls
94 lines (79 loc) · 1.9 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
using namespace std;
//Brute Force Approach
//Adding all elements in a set and checking for maximum XOR
// int findMaximumXOR(vector<int>&nums) {
// int maxXOR = 0;
// if(nums.size() < 2) return 0;
// int n = nums.size();
// for(int i = 0; i < n; i++) {
// for(int j = i+1; j < n; j++) {
// maxXOR = max(maxXOR, (nums[i] ^ nums[j]));
// }
// }
// return maxXOR;
// }
//Optimal Approach using Trie
struct Node {
Node*links[2];
bool containsKey(int bit) {
return links[bit] != NULL;
}
void put(int bit, Node* node) {
links[bit] = node;
}
Node*get(int bit) {
return links[bit];
}
};
class Trie {
Node*root;
public:
Trie() {
root = new Node();
}
void insert(int num) {
Node*node = root;
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);
}
}
int getMax(int num) {
Node*node = root;
int maxNum = 0;
for(int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
//searching for opposite bit
if(node->containsKey(1-bit)) {
maxNum = maxNum | (1 << i);
node = node->get(1-bit);
}
//oppostie bit not found
else {
node = node->get(bit);
}
}
return maxNum;
}
};
int findMaximumXOR(vector<int>&nums) {
Trie trie;
int maxXOR = 0;
if(nums.size() < 2) return 0;
for(auto &it : nums) {
trie.insert(it);
}
for(auto &it : nums) {
maxXOR = max(maxXOR, trie.getMax(it));
}
return maxXOR;
}
int main(){
vector<int>nums = {9,8,7,5,4};
cout << findMaximumXOR(nums) << endl;
return 0;
}