Maximize sum of Bitwise AND of same | C ++ program for the above approach ; Function to calculate sum of Bitwise AND of same indexed elements of the arrays p [ ] and arr [ ] ; Stores the resultant sum ; Traverse the array ; Update sum of Bitwise AND ; Return the value obtained ; Function to generate all permutations and calculate the maximum sum of Bitwise AND of same indexed elements present in any permutation and an array arr [ ] ; If the size of the array is N ; Calculate cost of permutation ; Generate all permutations ; Update chosen [ i ] ; Update the permutation p [ ] ; Generate remaining permutations ; Return the resultant sum ; Function to find the maximum sum of Bitwise AND of same indexed elements in a permutation of first N natural numbers and arr [ ] ; Stores the resultant maximum sum ; Stores the generated permutation P ; Function call to store result ; Print the result ; Driven Program ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcScore ( vector < int > p , int arr [ ] , int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += ( p [ i ] & arr [ i ] ) ; } return ans ; } int getMaxUtil ( vector < int > p , int arr [ ] , int ans , bool chosen [ ] , int N ) { if ( p . size ( ) == N ) { ans = max ( ans , calcScore ( p , arr , N ) ) ; return ans ; } for ( int i = 0 ; i < N ; i ++ ) { if ( chosen [ i ] ) { continue ; } chosen [ i ] = true ; p . push_back ( i ) ; ans = getMaxUtil ( p , arr , ans , chosen , N ) ; chosen [ i ] = false ; p . pop_back ( ) ; } return ans ; } void getMax ( int arr [ ] , int N ) { int ans = 0 ; bool chosen [ N ] ; for ( int i = 0 ; i < N ; i ++ ) chosen [ i ] = false ; vector < int > p ; int res = getMaxUtil ( p , arr , ans , chosen , N ) ; cout << res ; } int main ( ) { int arr [ ] = { 4 , 2 , 3 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMax ( arr , N ) ; return 0 ; }