- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum sum by adding numbers with same number of set bits in C++
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
#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
- Related Articles
- Maximum number of contiguous array elements with same number of set bits in C++
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Check if a number has same number of set and unset bits in C++
- Program to find higher number with same number of set bits as n in Python?
- Number of pairs with maximum sum in C++
- Minimum number using set bits of a given number in C++
- Count number of bits changed after adding 1 to given N in C++
- Maximum sum of distinct numbers with LCM as N in C++
- Represent a number as a Sum of Maximum Possible Number of Prime Numbers in C++
- Prime Number of Set Bits in Binary Representation in C++
- Maximum number with same digit factorial product in C++
- Count even length binary sequences with same sum of first and second half bits in C++
- Find next greater number with same set of digits in C++
- Minimum flips required to maximize a number with k set bits in C++.
