![]() |
VOOZH | about |
Given an integer array arr[] of size n and an integer k. The task is to find the maximum XOR of the subset of size k from the given array arr[].
Examples:
Input: arr[] = [2, 5, 4, 1, 3, 7, 6, 8], k = 3
Output: 15
Explanation: XOR of the elements of subset {2, 5, 8} is 15, which is the maximum possible.Input: arr[] = [3, 4, 7, 7, 9], k = 3
Output: 14
Explanation: XOR of the elements of subset {3, 4, 9} is 14, which is the maximum possible.Input: arr[] = [3, 4, 7, 16, 9], k = 1
Output: 16
Explanation: We need to select subset of size 1, thus the element with maximum value is the answer, which is 16.
Table of Content
The idea is to generate all possible subset of size k from the given array arr[], and find the one with XOR of its elements maximum. For each element, there two options, either include it into subset or exclude it. Firstly, exclude the element and move to the next one. Thereafter add the element in the current subset, and update the XOR. When the size of subset is k, check if the current XOR is greater than previous, if so, update the XOR value. At last return the maximum XOR.
Follow the below given step-by-step approach:
k, compare the XOR with the maximum XOR found so far and update if it's greater.k have been explored.Below is given the implementation:
15
The above approach can be optimized using Memoization. The idea is to store the results in a 3d array memo, to avoid computing the same subproblem multiple times. Create an array memo of order n * k * x, where n is the size of array, k is the size of subset, and x is the maximum XOR value (we are using unordered map). Here memo[i][j][x] stores the maximum possible XOR such that there are j elements in the subset up to index i with XOR x.
Follow the below given step-by-step approach:
memo[i][j][x], where:i is the current index in the array,j is the current size of the subset being formed,x is the current XOR value.k, return the current XOR value as a potential candidate for the maximum.Below is given the implementation:
15
Time Complexity: O(n * k * x), where n is the size of array, k is the size of subset, and x is the maximum possible XOR.
Auxiliary Space: O(n * k * x)