Maximum sum by adding numbers with same number of set bits in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of N numbers, the task is to find the maximum sum that can be obtained by adding numbers with the same number of set bits

Example

If input array is {2, 5, 8, 9, 10, 7} then output would be 14 −

• Number of set bits in 2 is 1

• Number of set bits in 5 is 2

• Number of set bits in 8 is 1

• Number of set bits in 9 is 2

• Number of set bits in 10 is 2

• Number of set bits in 7 is 3

Then sum of (5 + 9 + 10) is 24 whose number of set bits = 2

Algorithm

• Traverse in the array and count the number of set bits for every element.

• Initialize an array for 32 bits, assuming the number to have a maximum of 32 set bits.

• Iterate in the array and add the array element to the position which indicates the number of set bits.

• Traverse and find the maximum sum and return it.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int bitCount(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] = bitCount(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, 5, 8, 9, 10, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum sum = " << maxSum(arr, n) << endl;
return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum sum = 24
Published on 30-Jan-2020 12:13:59