Input: ‘N’ = 3 ‘ARR’ = [1, 2, 3] ‘K’ = 4
Output: 7
The subset [3] has the maximum possible value, which is equal to 3 XOR 4 = 7
The first line contains ‘T’, denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘K’.
The second line of each test case contains ‘N’ space-separated integers denoting the array ‘ARR’.
Return the maximum possible strength possible among all the subsets of array ‘ARR’.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= N <= 1000
0 <= ARR[i] <=1000 for ‘i’ in range 0 to N-1
0 <= K <= 1000
Time Limit: 1 sec
We can recursively try out all the possible subsets of the array. We have two options for every element of the array: either to take it in the subset or not. We call the recursive function for both of the cases and take the best of them.
We can keep the current strength in the recursive function and update it according to our choices in the subsequent calls.
When we reach the end of the array, we just return the current strength.xo
function getMaxStrengthUtil(int index, [int] ARR, int currStrength, int N):
We can use the memoization technique to store the result for each state with a particular ‘index’ and ‘currStrength.’ This way, we can save time from recalculating the already calculated results.
We can observe that in this problem, the result of bitwise XOR among all the possible operations will always be less than 210 because the ‘K’ and all array elements are less than
210 and therefore, the 10th bit and bits after the 10th bit will never be set
For memoization, let us define a 2-dimensional array DP of size (N+1) * 210
Where DP[ i ] [ j ] denotes maximum possible strength possible with ARR[ i…N-1 ] having currStrength as j
function getMaxStrength( [int] ARR , int N, int K):
The idea is the same as memoization. We are going to use recurrence relation :
DP [ i ] [ j ] = max ( DP [ i+1 ] [ j ] , DP [ i +1 ] [ j XOR ARR[ i ] ) with base case DP [ i ] [ j ] = j if i == N .
The idea behind this recurrence relation is that if we are at index ‘i’ having current strength as j then one option is to not put the current element in the subset and move forward which is DP [ i+1 ] [ j ] and the other option is to put it in the subset and move forward which is DP [ i + 1 ] [ j XOR ARR[ i ] ] and in the end, we choose best of these two options.
DP [ i ] [ j ] denotes the maximum strength possible for array ARR [ i … N-1 ] with currStrength as ‘ j ‘ .