<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>

const int MAX = 1e7 + 5;
struct Node {
    int left;
    int right;
    Node() : left(-1), right(-1) {}
};
Node nodes[MAX];
class Solution {
public:
    int idx = 0;
    int query(int node, int d, int val, int ans) {
        if (d == -1) {
            return ans;
        }
        int c = val & (1 << d);
        if (c == 0) {
            if (nodes[node].right != -1) {
                return query(nodes[node].right, d - 1, val, ans ^ (1 << d));
            } else {
                return query(nodes[node].left, d - 1, val, ans);
            }
        } else {
            if (nodes[node].left != -1) {
                return query(nodes[node].left, d - 1, val, ans ^ (1 << d));
            } else {
                return query(nodes[node].right, d - 1, val, ans);
            }
        }
    }

    void add(int node, int d, int val) {
        if (d < 0) {
            return;
        }
        int c = val & (1 << d);
        if (c == 0) {
            if (nodes[node].left == -1) {
                nodes[node].left = idx;
                nodes[idx++] = Node();
            }
            add(nodes[node].left, d - 1, val);
            return;
        } else {
            if (nodes[node].right == -1) {
                nodes[node].right = idx;
                nodes[idx++] = Node();
            }
            add(nodes[node].right, d - 1, val);
            return;
        }
    }


    int findMaximumXOR(vector<int>& nums) {
        nodes[idx++] = Node();
        add(0, 31, nums[0]);
        int ans = 0;
        for (int i = 1; i < nums.size(); i++) {
            int a = nums[i];
            ans = max(ans, query(0, 31, a, 0));
            add(0, 31, a);
        }
        return ans;
    }
};
126126