Maximize sum of Bitwise AND of same | Java 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int calcScore ( ArrayList < Integer > p , int arr [ ] ) { int ans = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { ans += ( p . get ( i ) & arr [ i ] ) ; } return ans ; } static int getMaxUtil ( ArrayList < Integer > p , int arr [ ] , int ans , boolean chosen [ ] , int N ) { if ( p . size ( ) == 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 . size ( ) - 1 ) ; } return ans ; } static void getMax ( int arr [ ] , int N ) { int ans = 0 ; boolean chosen [ ] = new boolean [ N ] ; ArrayList < Integer > p = new ArrayList < > ( ) ; int res = getMaxUtil ( p , arr , ans , chosen , N ) ; System . out . println ( res ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 3 , 6 } ; int N = arr . length ; getMax ( arr , N ) ; } }