Print pair with maximum AND value in an array | Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; Driver function
def checkBit ( pattern , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( pattern & arr [ i ] ) == pattern ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for bit in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT count = checkBit ( res | ( 1 << bit ) , arr , n ) NEW_LINE if ( count >= 2 ) : NEW_LINE INDENT res |= ( 1 << bit ) NEW_LINE DEDENT DEDENT if ( res == 0 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Pair ▁ = ▁ " , end = " " ) NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE while ( i < n and count < 2 ) : NEW_LINE INDENT if ( ( arr [ i ] & res ) == res ) : NEW_LINE INDENT count += 1 NEW_LINE print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum AND Value =   " , maxAND ( arr , n ) ) NEW_LINE