Find maximum xor of k elements in an array | Function to return the maximum xor for a subset of size k from the given array ; Initialize result ; Traverse all subsets of the array ; bitCount ( ) 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 ; Utility function ; Driver code
function Max_Xor ( arr , n , k ) { let maxXor = Number . MIN_VALUE ; for ( let i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( bitCount ( i ) == k ) { let cur_xor = 0 ; for ( let j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) cur_xor = cur_xor ^ arr [ j ] ; } maxXor = Math . max ( maxXor , cur_xor ) ; } } return maxXor ; } function bitCount ( x ) { let setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } let arr = [ 2 , 5 , 4 , 1 , 3 , 7 , 6 , 8 ] ; let n = arr . length ; let k = 3 ; document . write ( Max_Xor ( arr , n , k ) ) ;