Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array | Function to maximize the value for the given function and the array elements ; Vector array to maintain which bit is set for which integer in the given array by saving index of that integer ; Check if j - th bit is set for i - th integer ; Push the index of that integer in setBit [ j ] ; Find the element having highest significant set bit unset in other elements ; Place that integer at 0 - th index ; Store the maximum AND value ; Return the answer ; Driver Code ; Function call
def functionMax ( arr , n ) : NEW_LINE INDENT setBit = [ [ ] for i in range ( 32 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 32 ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << j ) ) : NEW_LINE INDENT setBit [ j ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT i = 31 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( len ( setBit [ i ] ) == 1 ) : NEW_LINE INDENT temp = arr [ 0 ] NEW_LINE arr [ 0 ] = arr [ setBit [ i ] [ 0 ] ] NEW_LINE arr [ setBit [ i ] [ 0 ] ] = temp NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT maxAnd = arr [ 0 ] NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT maxAnd = ( maxAnd & ( ~ arr [ i ] ) ) NEW_LINE DEDENT return maxAnd NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE print ( functionMax ( arr , n ) ) NEW_LINE DEDENT