Last active
October 31, 2020 04:16
-
-
Save Ch-sriram/5e897a97f4d4ac6e6571ab7a5d989707 to your computer and use it in GitHub Desktop.
Maximum Array XOR [TC: O(32*(2N)); SC: O(1)]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Problem Link: https://practice.geeksforgeeks.org/problems/maximum-subset-xor/1/ | |
// Good Explanation: https://www.geeksforgeeks.org/find-maximum-subset-xor-given-set/ | |
int maxSubarrayXOR(int arr[], int n) { | |
int maxEle = INT_MIN; | |
for(int i = 0; i < n; ++i) | |
maxEle = max(maxEle, arr[i]); | |
int MSB = 0; | |
for(int i = 31; i >= 0; --i) | |
if((1 << i) & maxEle) { | |
MSB = i; break; | |
} | |
int index = 0; | |
for(int i = MSB; i >= 0; --i, ++index) { | |
int maxIndex = index, maxElement = INT_MIN; | |
for(int j = index; j < n; ++j) | |
if((arr[j] & (1 << i)) && (arr[j] > maxElement)) | |
maxIndex = j, maxElement = arr[j]; | |
if(maxElement == INT_MIN) continue; // if there's no maxElement, there's no use going ahead. | |
swap(arr[index], arr[maxIndex]); // since we don't want to affect the number in 'index' position | |
maxIndex = index; // since now the position of maxElement is changed to 'index' in arr[] | |
for(int j = 0; j < n; ++j) | |
if(j != maxIndex && arr[j] & (1 << i)) | |
arr[j] ^= arr[maxIndex]; | |
} | |
int res = 0; | |
for(int i = 0; i < n; ++i) | |
res ^= arr[i]; | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem Link
Good Explanation