Maximize sum of Bitwise AND of same | 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
def calcScore ( p , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT ans += ( p [ i ] & arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMaxUtil ( p , arr , ans , chosen , N ) : NEW_LINE INDENT if len ( p ) == N : NEW_LINE INDENT ans = max ( ans , calcScore ( p , arr ) ) NEW_LINE return ans NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if chosen [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT chosen [ i ] = True NEW_LINE p . append ( i ) NEW_LINE ans = getMaxUtil ( p , arr , ans , chosen , N ) NEW_LINE chosen [ i ] = False NEW_LINE p . pop ( ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMax ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE chosen = [ False for i in range ( N ) ] NEW_LINE p = [ ] NEW_LINE res = getMaxUtil ( p , arr , ans , chosen , N ) NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 3 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE getMax ( arr , N ) NEW_LINE DEDENT