-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaximum_Xor_Subarray.cpp
122 lines (116 loc) · 3 KB
/
Maximum_Xor_Subarray.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
112
113
114
115
116
117
118
119
120
121
122
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
Node* left;
Node* right;
Node()
{
left = nullptr;
right = nullptr;
}
};
class Trie{
Node* root;
public:
Trie()
{
root = new Node();
}
void insertIntoTrie(int n)
{
Node* temp = root;
for(int i = 31 ; i >= 0 ; i--)
{
int bit = (n >> i) & 1 ;
if (bit == 0)
{
if (temp->left == nullptr)
{
Node* neww = new Node();
temp->left = neww;
temp = neww;
}
else
{
temp = temp->left;
}
}
else
{
if (temp->right == nullptr)
{
Node* neww = new Node();
temp->right = neww;
temp = neww;
}
else
{
temp = temp->right;
}
}
}
}
int max_xor_helper(int num)
{
int current_max_xor = 0;
Node* temp = root;
for(int i = 31 ; i >= 0 ; i--)
{
int bit = (num >> i) & 1;
if (bit == 0)
{
if (temp->right != nullptr)
{
current_max_xor += (1 << i);
temp = temp->right;
}
else
{
temp = temp->left;
}
}
else
{
if (temp->left != nullptr)
{
current_max_xor += (1 << i);
temp = temp->left;
}
else
{
temp = temp->right;
}
}
}
return current_max_xor;
}
int max_xor_subarray_finder(vector<int>& arr)
{
int n = arr.size();
int max_xor = 0;
for(int i = 0 ; i < n ; i++)
{
insertIntoTrie(arr[i]);
int current_val_max_xor = max_xor_helper(arr[i]);
max_xor = max(max_xor, current_val_max_xor);
}
return max_xor;
}
};
signed main() {
int n;
cin >> n;
vector<int> arr(n);
for(auto &ele: arr)
cin >> ele;
vector<int> prefix_xor;
int prefixXor = 0;
for(int i = 0 ; i < n ; i++)
{
prefixXor = prefixXor ^ arr[i];
prefix_xor.push_back(prefixXor);
}
Trie trie;
cout << trie.max_xor_subarray_finder(prefix_xor) << "\n";
}