Maximum XOR subarray
Given an array arr[] of size, N. Find the subarray with maximum XOR. A subarray is a contiguous part of the array.
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
| struct Trie { Trie* next[2]; bool eof = false; Trie() { memset(next, 0, sizeof next); } void insert(int n, int mask = 17) { if(mask == -1) eof = true; else { bool bit = n & (1<<mask); if(!next[bit]) next[bit] = new Trie(); next[bit]->insert(n, mask - 1); } } int query(int n, int mask = 17) { if(mask == -1) return 0; bool bit = n & (1<<mask); if(next[!bit]) return (1<<mask) + next[!bit]->query(n, mask - 1); if(next[bit]) return next[bit]->query(n, mask - 1); return n & ((1<<(mask + 1)) - 1); } }; class Solution{ public: int maxSubarrayXOR(int N, int arr[]){ Trie* t = new Trie(); int res = 0, XOR = 0; t->insert(0); for(int i = 0; i < N; i++) { XOR ^= arr[i]; res = max(res, t->query(XOR)); t->insert(XOR); } return res; } };
|