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

#include <array>
#include <vector>

using std::array, std::vector;

const int MAX_BIT = 31;

struct Node {
    array<Node*, 2> children{};
};

class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        for (int num : nums) {
            std::cout << std::bitset<MAX_BIT + 1>(num) << "\n";
        }

        Node* trie = new Node{};
        for (int num : nums) {
            add_num(trie, num, 0);
        }

        int max_xor = 0;
        for (int num : nums) {
            int alternate = find_alternate(trie, num, 0);
            if ((num ^ alternate) > max_xor) {
                max_xor = num ^ alternate;
            }
        }

        return max_xor;
    }

private:
    void add_num(Node* node, int num, int pos) {
        int bit = (num >> (MAX_BIT - pos)) & 1;
        if (!node->children[bit]) {
            node->children[bit] = new Node{};
        }
        if (pos < MAX_BIT) {
            add_num(node->children[bit], num, pos + 1);
        }
    }

    int find_alternate(Node* node, int num, int pos) {
        int shift = MAX_BIT - pos;
        int bit = (num >> shift) & 1;
        if (node->children[1 - bit]) {
            if (pos < MAX_BIT) {
                return ((1 - bit) << shift) | find_alternate(node->children[1 - bit], num, pos + 1);
            }
            return (1 - bit) << shift;
        } else if (node->children[bit]) {
            if (pos < MAX_BIT) {
                return (bit << shift) | find_alternate(node->children[bit], num, pos + 1);
            }
            return bit << shift;
        }
        return bit << shift;
    }

    void print_trie(Node* node, int depth) {
        for (int bit = 0; bit <= 1; bit ++) {
            if (node->children[bit]) {
                std::cout << string(depth * 2, ' ') << bit << "\n";
                print_trie(node->children[bit], depth + 1);
            }
        }
    }
};
225276