Find maximum xor of k elements in an array | Java implementation of the approach ; Function to return the maximum xor for a subset of size k from the given array ; Initialize result ; Traverse all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; Initialize current xor as 0 ; If jth bit is set in i then include jth element in the current xor ; Update maximum xor so far ; Driver code
import java . util . * ; class GFG { static int Max_Xor ( int arr [ ] , int n , int k ) { int maxXor = Integer . MIN_VALUE ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( Integer . bitCount ( i ) == k ) { int cur_xor = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) == 0 ) cur_xor = cur_xor ^ arr [ j ] ; } maxXor = Math . max ( maxXor , cur_xor ) ; } } return maxXor ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 4 , 1 , 3 , 7 , 6 , 8 } ; int n = arr . length ; int k = 3 ; System . out . println ( Max_Xor ( arr , n , k ) ) ; } }