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 code
< ? php function checkBit ( $ pattern , $ arr , $ n ) { $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( ( $ pattern & $ arr [ $ i ] ) == $ pattern ) $ count ++ ; return $ count ; } function maxAND ( $ arr , $ n ) { $ res = 0 ; for ( $ bit = 31 ; $ bit >= 0 ; $ bit -- ) { $ count = checkBit ( $ res | ( 1 << $ bit ) , $ arr , $ n ) ; if ( $ count >= 2 ) $ res |= ( 1 << $ bit ) ; } if ( $ res == 0 ) echo " Not ▁ Possible STRNEWLINE " ; else { echo " Pair = " $ count = 0 ; for ( $ i = 0 ; $ i < $ n && $ count < 2 ; $ i ++ ) { if ( ( $ arr [ $ i ] & $ res ) == $ res ) { $ count ++ ; echo $ arr [ $ i ] . " " ; } } } return $ res ; } $ arr = array ( 4 , 8 , 6 , 2 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo " Maximum AND Value = " ? >