Maximum sum by adding numbers with same number of set bits | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bit_count ( int n ) { int count = 0 ; while ( n ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } int maxsum ( int arr [ ] , int n ) { int bits [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { bits [ i ] = bit_count ( arr [ i ] ) ; } int sum [ 32 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { sum [ bits [ i ] ] += arr [ i ] ; } int maximum = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { maximum = max ( sum [ i ] , maximum ) ; } return maximum ; } int main ( ) { int arr [ ] = { 2 , 3 , 8 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxsum ( arr , n ) ; return 0 ; }