<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,10,5,25,2,8]
<strong>Output:</strong> 28
<strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70]
<strong>Output:</strong> 127
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class TrieNode {
public:
    TrieNode* ch[2];
};

class Solution {
    int get_num_bits(int num) {
        int c = 0;
        for(int i=0; i<32; i++) {
            int bit = 1<<i;
            if(bit & num) c = i;
        }
        return c+1;
    }
    string convert_to_string(int num, int size) {
        string s = string(size, '0');
        for(int i=size-1; i>=0; --i) {
            if(num) s[i] = '0' + (num%2);
            else s[i] = '0';
            num /= 2;
        }
        return s;
    }
    int calculate_ans(string a, string b) {
        int calc = 0;
        for(int idx=a.size()-1; idx>=0; --idx) {
            int bit = 1 << a.size() - idx - 1;
            if(a[idx] != b[idx]) {
                calc |= bit;
            }
        }
        return calc;
    }
public:
    int findMaximumXOR(vector<int>& nums) {
        int max_ele = *max_element(nums.begin(), nums.end());
        int size = get_num_bits(max_ele);
        vector<string> numbers;
        for(int i=0; i<nums.size(); ++i) {
            numbers.push_back(convert_to_string(nums[i], size));
        }
        TrieNode* root = new TrieNode();
        
        // now construct the trie and append elements one by one
        for(int idx=0; idx<numbers.size(); ++idx) {
            TrieNode* ptr = root;
            for(char c: numbers[idx]) {
                if(ptr->ch[c-'0'] == NULL) {
                    ptr->ch[c-'0'] = new TrieNode();
                }
                ptr = ptr->ch[c-'0'];
            }
        }
        int result = 0;
        for(int idx=0; idx<numbers.size(); ++idx) {
            TrieNode* ptr = root;
            string t = "";
            for(char c: numbers[idx]) {
                // try to find the max opposite, or else switch that only
                char target = c == '0'? '1':'0';
                if(ptr->ch[target-'0'] != NULL) {
                    t += target;
                    ptr = ptr->ch[target-'0'];
                } else {
                    t += c;
                    ptr = ptr->ch[c-'0'];
                }
            }
            result = max(result, calculate_ans(numbers[idx], t));
        }
        return result;
    }
};

284766