Find maximum xor of k elements in an array | C # 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 ; Utility function ; Driver code
using System ; class GFG { static int Max_Xor ( int [ ] arr , int n , int k ) { int maxXor = int . MinValue ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( 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 ; } static int bitCount ( long x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 5 , 4 , 1 , 3 , 7 , 6 , 8 } ; int n = arr . Length ; int k = 3 ; Console . WriteLine ( Max_Xor ( arr , n , k ) ) ; } }