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 prleting element ; return the result value ; Driver code
function checkBit ( pattern , arr , n ) { let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( ( pattern & arr [ i ] ) == pattern ) count ++ ; return count ; } function maxAND ( arr , n ) { let res = 0 , count ; for ( let bit = 31 ; bit >= 0 ; bit -- ) { count = checkBit ( res | ( 1 << bit ) , arr , n ) ; if ( count >= 2 ) res |= ( 1 << bit ) ; } if ( res == 0 ) System . out . prletln ( " " ) ; else { document . write ( " " ) ; count = 0 ; for ( let i = 0 ; i < n && count < 2 ; i ++ ) { if ( ( arr [ i ] & res ) == res ) { count ++ ; document . write ( arr [ i ] + " " ) ; } } document . write ( " " ) ; } return res ; } let arr = [ 4 , 8 , 6 , 2 ] ; let n = arr . length ; document . write ( " " + maxAND ( arr , n ) ) ;