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
def bit_count ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE n = n & ( n - 1 ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def maxsum ( arr , n ) : NEW_LINE INDENT bits = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT bits [ i ] = bit_count ( arr [ i ] ) ; NEW_LINE DEDENT sum = [ 0 ] * 32 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum [ bits [ i ] ] += arr [ i ] ; NEW_LINE DEDENT maximum = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT maximum = max ( sum [ i ] , maximum ) ; NEW_LINE DEDENT return maximum ; NEW_LINE DEDENT arr = [ 2 , 3 , 8 , 5 , 6 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxsum ( arr , n ) ) ; NEW_LINE