Maximum sum by adding numbers with same number of set bits | count the number of bits for each element of array ; Count the number of set bits ; Function to return the the maximum sum ; Calculate the ; Assuming the number to be a maximum of 32 bits ; Add the number to the number of set bits ; Find the maximum sum ; Driver code
< ? php function bit_count ( $ n ) { $ count = 0 ; while ( $ n ) { $ count ++ ; $ n = $ n & ( $ n - 1 ) ; } return $ count ; } function maxsum ( $ arr , $ n ) { $ bits = array ( $ n ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ bits [ $ i ] = bit_count ( $ arr [ $ i ] ) ; } $ sum = array_fill ( 0 , 32 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ sum [ $ bits [ $ i ] ] += $ arr [ $ i ] ; } $ maximum = 0 ; for ( $ i = 0 ; $ i < 32 ; $ i ++ ) { $ maximum = max ( $ sum [ $ i ] , $ maximum ) ; } return $ maximum ; } $ arr = array ( 2 , 3 , 8 , 5 , 6 , 7 ) ; $ n = sizeof ( $ arr ) ; echo maxsum ( $ arr , $ n ) ; ? >