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 ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int calcScore ( List < int > p , int [ ] arr ) { int ans = 0 ; for ( int i = 0 ; i < arr . Length ; i ++ ) { ans += ( p [ i ] & arr [ i ] ) ; } return ans ; } static int getMaxUtil ( List < int > p , int [ ] arr , int ans , bool [ ] chosen , int N ) { if ( p . Count == N ) { ans = Math . Max ( ans , calcScore ( p , arr ) ) ; return ans ; } for ( int i = 0 ; i < N ; i ++ ) { if ( chosen [ i ] ) { continue ; } chosen [ i ] = true ; p . Add ( i ) ; ans = getMaxUtil ( p , arr , ans , chosen , N ) ; chosen [ i ] = false ; p . Remove ( p . Count - 1 ) ; } return ans ; } static void getMax ( int [ ] arr , int N ) { int ans = 0 ; bool [ ] chosen = new bool [ N ] ; List < int > p = new List < int > ( ) ; int res = getMaxUtil ( p , arr , ans , chosen , N ) ; Console . Write ( res ) ; } public static void Main ( ) { int [ ] arr = { 4 , 2 , 3 , 6 } ; int N = arr . Length ; getMax ( arr , N ) ; } }