Maximum sum of Bitwise XOR of elements with their respective positions in a permutation of size N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcScr ( vector < int > arr ) { int ans = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) ans += ( i ^ arr [ i ] ) ; return ans ; } int getMax ( vector < int > arr , int ans , vector < bool > chosen , int N ) { if ( arr . size ( ) == N ) { ans = max ( ans , calcScr ( arr ) ) ; return ans ; } for ( int i = 0 ; i < N ; i ++ ) { if ( chosen [ i ] ) continue ; chosen [ i ] = true ; arr . push_back ( i ) ; ans = getMax ( arr , ans , chosen , N ) ; chosen [ i ] = false ; arr . pop_back ( ) ; } return ans ; } int main ( ) { int N = 2 ; vector < int > arr ; int ans = -1 ; vector < bool > chosen ( N , false ) ; ans = getMax ( arr , ans , chosen , N ) ; cout << ans << endl ; }