Maximum Subarray XOR
Solve a hard-level problem for finding the maximum subarray XOR value in an array using tries.
Problem statement
Given an array nums
of integers, find the maximum subarray XOR value in the given array.
Example 1
Sample input
nums: [1,2,3,4]
Sample output
7
Explanation
The subarray [3, 4]
has maximum XOR value of 7
.
Example 2
Sample input
[8,1,2,12,7,6]
Sample output
15
Explanation
The subarray [1,2,12]
has the maximum XOR value of 15
.
Try it yourself
Try to solve the problem yourself before reading the solution.
#include <iostream>#include <vector>using namespace std;int maxSubarrayXOR(vector<int> nums) {// your code goes herereturn -1;}
Intuition
A brute force solution finds the XOR of all possible subarrays and then extracts the maximum value. We iterate from
#include<bits/stdc++.h>using namespace std;int maxSubarrayXOR(vector<int> nums) {// Initialize resultint ans = INT_MIN;// Pick starting points of subarraysfor (int i=0; i<nums.size(); i++) {// to store xor of current subarrayint currXOR = 0;// Pick ending points of subarrays starting with ifor (int j=i; j<nums.size(); j++) {currXOR = currXOR ^ nums[j];ans = max(ans, currXOR);}}return ans;}// Driver program to test maxSubarrayXOR functionint main() {vector<int> nums = {8, 1, 2, 12};cout << maxSubarrayXOR(nums);return 0;}
Complexity analysis
In the above code, we iterate over the input array in a nested loop, resulting in a time complexity of
Only a single variable, currXOR
, is created to store the final answer. So the ...