Maximum XOR subset - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Saturday 25 July 2020

Maximum XOR subset

Maximum XOR subset
Maximum XOR subset
                        
                           
Maximum subset XOR

Given a set of positive integers. The task is to complete the function maxSubarrayXOR which returns an integer denoting the maximum XOR subset value in the given set.

Input:
3
3
2 4 5 
3
33 73 64
9
5 633 64 43 131 51 87 999 23 

Output:
7
104
1023

#include <bits/stdc++.h>
using namespace std;
//maximum value of n is 30 and maximum value of array element is 1000
int dp[30][1000];
int findSx(int a[],int i,int x)
{
//if i is less then 0 then return x bcoz x is xor sum value
    if(i<0)
    return x;
//if dp[i][x] is not zero then return value else calculate this value
// that mean if dp[i][x] is already calculated then there is no need to calculate again
    if(dp[i][x])
    return dp[i][x];
    return dp[i][x]=max(findSx(a,i-1,x^a[i]),findSx(a,i-1,x));
//return maximum value by taking or ignore a[i]
}
int main() {
    //code
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int a[n];
        for(int i=0;i<n;++i)
        {
         cin>>a[i];
        }
        // initialize the dp with 0
        memset(dp,0,sizeof(dp));
     //find the xor subset from array
        cout<<findSx(a,n-1,0)<<endl;
    }
    return 0;
}