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
function bit_count ( n ) { var count = 0 ; while ( n ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } function maxsum ( arr , n ) { var bits = Array ( n ) ; for ( var i = 0 ; i < n ; i ++ ) { bits [ i ] = bit_count ( arr [ i ] ) ; } var sum = Array ( 32 ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { sum [ bits [ i ] ] += arr [ i ] ; } var maximum = 0 ; for ( var i = 0 ; i < 32 ; i ++ ) { maximum = Math . max ( sum [ i ] , maximum ) ; } return maximum ; } var arr = [ 2 , 3 , 8 , 5 , 6 , 7 ] ; var n = arr . length ; document . write ( maxsum ( arr , n ) ) ;