Find the maximum subset XOR of a given set | Java program to find maximum XOR subset ; Number of bits to represent int ; Function to return maximum XOR subset in set [ ] ; Initialize index of chosen elements ; Traverse through all bits of integer starting from the most significant bit ( MSB ) ; Initialize index of maximum element and the maximum element ; If i 'th bit of set[j]  is set and set[j] is  greater than max so far. ; If there was no element with i 'th  bit set, move to  smaller i ; Put maximum element with i ' th ▁ bit ▁ set ▁ ▁ at ▁ index ▁ ' index ' ; Update maxInd and increment index ; Do XOR of set [ maxIndex ] with all numbers having i 'th bit as set. ; XOR set [ maxInd ] those numbers which have the i 'th bit set ; Increment index of chosen elements ; Final result is XOR of all elements ; Driver code
import java . util . * ; class GFG { static final int INT_BITS = 32 ; static int maxSubarrayXOR ( int set [ ] , int n ) { int index = 0 ; for ( int i = INT_BITS - 1 ; i >= 0 ; i -- ) { int maxInd = index ; int maxEle = Integer . MIN_VALUE ; for ( int j = index ; j < n ; j ++ ) { if ( ( set [ j ] & ( 1 << i ) ) != 0 && set [ j ] > maxEle ) { maxEle = set [ j ] ; maxInd = j ; } } if ( maxEle == - 2147483648 ) continue ; int temp = set [ index ] ; set [ index ] = set [ maxInd ] ; set [ maxInd ] = temp ; maxInd = index ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != maxInd && ( set [ j ] & ( 1 << i ) ) != 0 ) set [ j ] = set [ j ] ^ set [ maxInd ] ; } index ++ ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res ^= set [ i ] ; return res ; } public static void main ( String arg [ ] ) { int set [ ] = { 9 , 8 , 5 } ; int n = set . length ; System . out . print ( " Max ▁ subset ▁ XOR ▁ is ▁ " ) ; System . out . print ( maxSubarrayXOR ( set , n ) ) ; } }