Sponsored
Sponsored
This approach involves iterating over all possible pairs of numbers in the array and calculating their XOR. We keep track of the maximum XOR value encountered during these iterations.
Though straightforward, this method is not efficient for large arrays, as it involves checking each pair of numbers.
Time Complexity: O(n^2), where n is the number of elements in the array, because it checks every pair.
Space Complexity: O(1), as it uses only a constant amount of space.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int findMaximumXOR(vector<int>& nums) {
6 int maxXor = 0;
7 for (size_t i = 0; i < nums.size(); ++i) {
8 for (size_t j = i; j < nums.size(); ++j) {
9 int xorValue = nums[i] ^ nums[j];
10 maxXor = max(maxXor, xorValue);
11 }
12 }
13 return maxXor;
14}
15
16int main() {
17 vector<int> nums = {3, 10, 5, 25, 2, 8};
18 cout << "Maximum XOR: " << findMaximumXOR(nums) << endl;
19 return 0;
20}
The function findMaximumXOR
iterates over all possible pairs of numbers in the array nums
, computing the XOR for each pair and keeping track of the maximum XOR value. The method uses a nested loop to go through each pair combination.
This approach makes use of a Trie data structure to efficiently maximize the XOR computation. By examining the binary representation of numbers, we can leverage the Trie to only explore branches that potentially maximize the XOR result.
The Trie helps in finding complementary patterns (bits) efficiently by using bit manipulation and path traversal.
Time Complexity: O(n * W), where n is the number of elements and W is the number of bits in the maximum number.
Space Complexity: O(n * W), for storing the Trie.
This solution constructs a Trie to store the binary representation of each number. As each number is inserted into the Trie, we simultaneously seek to maximize the XOR by traversing potentially complementing paths (opposite bits in Trie nodes).