-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Max_XOR_of_Two_Array.cpp
111 lines (94 loc) · 2.39 KB
/
Max_XOR_of_Two_Array.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
Given an integer array nums, return the maximum result of nums[i] XOR nums[j],
where 0 ≤ i ≤ j < n.
*/
#include<iostream>
#include<vector>
using namespace std;
// Constructing a trie
struct trie {
trie *zero,*one;
};
//Building the trie
void insert(int num,trie *root) {
trie *ptr=root;
for(int i=31;i>=0;i--) {
int h = (num>>i & 1);
if(h==0) {
if(ptr->zero==NULL) {
ptr->zero=new trie();
}
ptr=ptr->zero;
}
else {
if(ptr->one==NULL) {
ptr->one=new trie();
}
ptr=ptr->one;
}
}
}
//Finding the maximum XOR for each element
int comp(int num,trie *root) {
trie *ptr = root;
int sum=0;
for(int i=31;i>=0;i--) {
sum=sum<<1;
int h = (num>>i & 1);
if(h==0) {
if(ptr->one) {
sum++;
ptr=ptr->one;
}
else ptr=ptr->zero;
}
else {
if(ptr->zero) {
sum++;
ptr=ptr->zero;
}
else ptr=ptr->one;
}
}
return sum;
}
int findMaximumXOR(vector<int>& nums) {
trie *root = new trie();
for(int i=0;i<nums.size();i++) {
insert(nums[i],root);
}
int maxm=0;
for(int i=0;i<nums.size();i++) {
maxm=max(comp(nums[i],root),maxm);
}
return maxm;
}
//Main Function
int main() {
vector<int>nums;
int sz;
cout<<"Enter the vector size\n";
cin>>sz; // size of the vector
cout<<"Enter the elements in the vector\n";
for(int i=0;i<sz;i++) {
int x;
cin>>x;
nums.push_back(x);
}
int answer = findMaximumXOR(nums);
cout<<"The Maximum XOR of two numbers in the array/vector is : "<<answer<<endl;
return 0;
}
/* Sample Text Case
Enter the vector size
6
Enter the elements in the vector
3 10 5 25 2 8
The Maximum XOR of two numbers in the array/vector is : 28
Enter the vector size
12
Enter the elements in the vector
14 70 53 83 49 91 36 80 92 51 66 70
The Maximum XOR of two numbers in the array/vector is : 127
Time Complexity : O(n) , where n is the number of elements in the vector.
*/