Maximum sum of Bitwise XOR of elements with their respective positions in a permutation of size N | Java program for the above approach ; Function to calculate the score ; Stores the possible score for the current permutation ; Traverse the permutation array ; Return the final score ; Function to generate all the possible permutation and get the max score ; If arr [ ] length is equal to N process the permutation ; Generating the permutations ; If the current element is chosen ; Mark the current element as true ; Recursively call for next possible permutation ; Backtracking ; Return the ans ; Driver Code ; Stores the permutation ; To display the result
import java . util . * ; class GFG { static int calcScr ( ArrayList < Integer > arr ) { int ans = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) ans += ( i ^ arr . get ( i ) ) ; return ans ; } static int getMax ( ArrayList < Integer > arr , int ans , ArrayList < Boolean > chosen , int N ) { if ( arr . size ( ) == N ) { ans = Math . max ( ans , calcScr ( arr ) ) ; return ans ; } for ( int i = 0 ; i < N ; i ++ ) { if ( chosen . get ( i ) ) continue ; chosen . set ( i , true ) ; arr . add ( i ) ; ans = getMax ( arr , ans , chosen , N ) ; chosen . set ( i , false ) ; arr . remove ( arr . size ( ) - 1 ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 2 ; ArrayList < Integer > arr = new ArrayList < Integer > ( ) ; int ans = - 1 ; ArrayList < Boolean > chosen = new ArrayList < Boolean > ( Collections . nCopies ( N , false ) ) ; ans = getMax ( arr , ans , chosen , N ) ; System . out . print ( ans + "NEW_LINE"); } }