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.
1public class Solution {
2 public int findMaximumXOR(int[] nums) {
3 int maxXor = 0;
4 for (int i = 0; i < nums.length; i++) {
5 for (int j = i; j < nums.length; j++) {
6 int xorValue = nums[i] ^ nums[j];
7 if (xorValue > maxXor) {
8 maxXor = xorValue;
9 }
10 }
11 }
12 return maxXor;
13 }
14
15 public static void main(String[] args) {
16 int[] nums = {3, 10, 5, 25, 2, 8};
17 Solution solution = new Solution();
18 System.out.println("Maximum XOR: " + solution.findMaximumXOR(nums));
19 }
20}
21
This Java solution iteratively calculates the XOR for each pair of elements in the input array. It updates the maximum XOR found and then returns it. The findMaximumXOR
method loops over each unique pair, computing and comparing XOR values.
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 Python solution adds numbers into a Trie and attempts to maximize the XOR result by exploring complementary bit paths during insertion and traversal.