Maximum sum by adding numbers with same number of set bits | Java program to find 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
class GFG { static int bit_count ( int n ) { int count = 0 ; while ( n > 0 ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } static int maxsum ( int [ ] arr , int n ) { int [ ] bits = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { bits [ i ] = bit_count ( arr [ i ] ) ; } int [ ] sum = new int [ 32 ] ; for ( int i = 0 ; i < n ; i ++ ) { sum [ bits [ i ] ] += arr [ i ] ; } int maximum = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { maximum = Math . max ( sum [ i ] , maximum ) ; } return maximum ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 8 , 5 , 6 , 7 } ; int n = arr . length ; System . out . println ( maxsum ( arr , n ) ) ; } }