Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Maximum multiple of a number with all digits same
Next article icon

Maximum sum by adding numbers with same number of set bits

Last Updated : 01 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 
Examples: 
 

Input: 32 3 7 5 27 28 
Output: 34
Input: 2 3 8 5 6 7 
Output: 14
 


 


 


Approach: 
 

  • 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.


Below is the implementation of the above approach: 
 

C++
// C++ program to find maximum sum // by adding numbers with same number of set bits #include <bits/stdc++.h> using namespace std;  // count the number of bits // for each element of array int bit_count(int n) {     int count = 0;      // Count the number of set bits     while (n) {         count++;          n = n & (n - 1);     }      return count; }  // Function to return the // the maximum sum int maxsum(int arr[], int n) {     int bits[n];      // Calculate the     for (int i = 0; i < n; i++) {         bits[i] = bit_count(arr[i]);     }      // Assuming the number to be     // a maximum of 32 bits     int sum[32] = { 0 };      // Add the number to the     // number of set bits     for (int i = 0; i < n; i++) {         sum[bits[i]] += arr[i];     }      int maximum = 0;      // Find the maximum sum     for (int i = 0; i < 32; i++) {          maximum = max(sum[i], maximum);     }      return maximum; }  // Driver code int main() {      int arr[] = { 2, 3, 8, 5, 6, 7 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << maxsum(arr, n);      return 0; } 
C
// C program to find maximum sum // by adding numbers with same number of set bits #include <stdio.h> #include <stdlib.h> #include<math.h>  //function to find the maximum of two numbers  int max(int a,int b) { if(a>b)     return a; else     return b; }  // count the number of bits // for each element of array  int bit_count(int n) {     int count = 0;      // Count the number of set bits     while (n) {         count++;          n = n & (n - 1);     }      return count; }  // Function to return the // the maximum sum int maxsum(int arr[], int n) {     int bits[n];      // Calculate the     for (int i = 0; i < n; i++) {         bits[i] = bit_count(arr[i]);     }      // Assuming the number to be     // a maximum of 32 bits     int sum[32] = { 0 };      // Add the number to the     // number of set bits     for (int i = 0; i < n; i++) {         sum[bits[i]] += arr[i];     }      int maximum = 0;      // Find the maximum sum     for (int i = 0; i < 32; i++) {          maximum = max(sum[i], maximum);     }      return maximum; }  // Driver code int main() {      int arr[] = { 2, 3, 8, 5, 6, 7 };     int n = sizeof(arr) / sizeof(arr[0]);     int ans=maxsum(arr,n);     printf("%d",ans);     return 0; } 
Java
// Java program to find maximum sum // by adding numbers with same number of set bits  class GFG { // count the number of bits // for each element of array static int bit_count(int n) {     int count = 0;      // Count the number of set bits     while (n>0)     {         count++;          n = n & (n - 1);     }      return count; }  // Function to return the // the maximum sum static int maxsum(int[] arr, int n) {     int[] bits=new int[n];      // Calculate the     for (int i = 0; i < n; i++)      {         bits[i] = bit_count(arr[i]);     }      // Assuming the number to be     // a maximum of 32 bits     int[] sum=new int[32];      // Add the number to the     // number of set bits     for (int i = 0; i < n; i++)     {         sum[bits[i]] += arr[i];     }      int maximum = 0;      // Find the maximum sum     for (int i = 0; i < 32; i++)     {          maximum = Math.max(sum[i], maximum);     }      return maximum; }  // Driver code public static void main (String[] args) {     int[] arr = { 2 ,3 , 8, 5, 6, 7 };     int n = arr.length;     System.out.println(maxsum(arr, n));  } }  // This Code is contributed by mits 
Python3
# Python3 program to find maximum # sum by adding numbers with # same number of set bits  # count the number of bits # for each element of array def bit_count(n):     count = 0;      # Count the number     # of set bits     while (n > 0):         count += 1;          n = n & (n - 1);      return count;  # Function to return the # the maximum sum def maxsum(arr, n):     bits = [0] * n;      # Calculate the     for i in range(n):          bits[i] = bit_count(arr[i]);      # Assuming the number to be     # a maximum of 32 bits     sum = [0] * 32;      # Add the number to the     # number of set bits     for i in range(n):          sum[bits[i]] += arr[i];      maximum = 0;      # Find the maximum sum     for i in range(32):          maximum = max(sum[i], maximum);      return maximum;  # Driver code arr = [ 2, 3, 8, 5, 6, 7 ]; n = len(arr); print(maxsum(arr, n));  # This code is contributed by mits 
C#
// C# program to find maximum  // sum by adding numbers with  // same number of set bits using System;  class GFG { // count the number of bits // for each element of array static int bit_count(int n) {     int count = 0;      // Count the number     // of set bits     while (n > 0)     {         count++;          n = n & (n - 1);     }      return count; }  // Function to return the // the maximum sum static int maxsum(int[] arr, int n) {     int[] bits = new int[n];      // Calculate the     for (int i = 0; i < n; i++)      {         bits[i] = bit_count(arr[i]);     }      // Assuming the number to be     // a maximum of 32 bits     int[] sum = new int[32];      // Add the number to the     // number of set bits     for (int i = 0; i < n; i++)     {         sum[bits[i]] += arr[i];     }      int maximum = 0;      // Find the maximum sum     for (int i = 0; i < 32; i++)     {         maximum = Math.Max(sum[i], maximum);     }      return maximum; }  // Driver code static void Main() {     int[] arr = { 2 ,3 , 8, 5, 6, 7 };     int n = arr.Length;     Console.WriteLine(maxsum(arr, n)); } }  // This Code is contributed by mits 
PHP
<?php // PHP program to find maximum // sum by adding numbers with // same number of set bits  // count the number of bits // for each element of array function bit_count($n) {     $count = 0;      // Count the number     // of set bits     while ($n)     {         $count++;          $n = $n & ($n - 1);     }      return $count; }  // Function to return the // the maximum sum function maxsum($arr, $n) {     $bits = array($n);      // Calculate the     for ($i = 0; $i < $n; $i++)      {         $bits[$i] = bit_count($arr[$i]);     }      // Assuming the number to be     // a maximum of 32 bits     $sum = array_fill(0, 32, 0);      // Add the number to the     // number of set bits     for ($i = 0; $i < $n; $i++)      {         $sum[$bits[$i]] += $arr[$i];     }      $maximum = 0;      // Find the maximum sum     for ($i = 0; $i < 32; $i++)     {          $maximum = max($sum[$i],                        $maximum);     }      return $maximum; }  // Driver code $arr = array( 2, 3, 8, 5, 6, 7 ); $n = sizeof($arr); echo maxsum($arr, $n);  // This code is contributed by mits ?> 
JavaScript
<script>  // Javascript program to find maximum sum // by adding numbers with same number of set bits  // count the number of bits // for each element of array function bit_count(n) {     var count = 0;      // Count the number of set bits     while (n) {         count++;          n = n & (n - 1);     }      return count; }  // Function to return the // the maximum sum function maxsum(arr, n) {     var bits = Array(n);      // Calculate the     for (var i = 0; i < n; i++) {         bits[i] = bit_count(arr[i]);     }      // Assuming the number to be     // a maximum of 32 bits     var sum = Array(32).fill(0);      // Add the number to the     // number of set bits     for (var i = 0; i < n; i++) {         sum[bits[i]] += arr[i];     }      var maximum = 0;      // Find the maximum sum     for (var i = 0; i < 32; i++) {          maximum = Math.max(sum[i], maximum);     }      return maximum; }  // Driver code var arr = [2, 3, 8, 5, 6, 7]; var n = arr.length; document.write( maxsum(arr, n));  // This code is contributed by famously. </script>  

Output: 
14

 

Time Complexity: O(N * 32) 
Auxiliary Space: O(N)
 


Next Article
Maximum multiple of a number with all digits same

M

Mohd_Saliem
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Algorithms-Greedy Algorithms
  • Algorithms-Bit Algorithms
Practice Tags :
  • Bit Magic

Similar Reads

  • Next higher number with same number of set bits
    Given a number x, find next number with same number of 1 bits in it's binary representation.For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).Algorit
    8 min read
  • Maximum number of contiguous array elements with same number of set bits
    Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8}
    6 min read
  • Closest (or Next) smaller and greater numbers with same number of set bits
    Given a positive integer n, print the next smallest and the previous largest number that has the same number of 1 bit in their binary representation. Examples: Input : n = 5 Output : Closest Greater = 6 Closest Smaller = 3 Note that 5, 6 and 3 have same number of set bits. Input : n = 11 Output : Cl
    15+ min read
  • Maximum multiple of a number with all digits same
    Given two positive integers X and Y (1 ? Y ? 105), find the maximum positive multiple (say M) of X such that M is less than 10Y and all the digits in the decimal representation of M are equal. Note: If no positive multiple exists that satisfies the conditions, return -1. Examples: Input: X = 1, Y =
    7 min read
  • Check if a number has same number of set and unset bits
    Given a number N, the task is to check whether the count of the set and unset bits in the given number are same. Examples: Input: 12Output: Yes1100 is the binary representation of 12which has 2 set and 2 unset bits Input: 14Output: No Approach: Traverse in the binary representation of the given numb
    5 min read
  • Minimum number using set bits of a given number
    Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number. Examples : Input : 6 Output : 3 Binary representation of 6 is 0000....0110. Smallest number with same number of set bits 0000....0011. Input : 11 Output : 7 Simple Approach: 1. Find
    4 min read
  • M-th smallest number having k number of set bits.
    Given two non-negative integers m and k. The problem is to find the m-th smallest number having k number of set bits.Constraints: 1 <= m, k.Examples: Input : m = 4, k = 2 Output : 9 (9)10 = (1001)2, it is the 4th smallest number having 2 set bits. Input : m = 6, k = 4 Output : 39 Approach: Follow
    6 min read
  • Minimum number of Binary strings to represent a Number
    Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples: Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 11
    7 min read
  • Sum of numbers with exactly 2 bits set
    Given a number n. Find the sum of all numbers up to n whose 2 bits are set. Examples: Input : 10 Output : 33 3 + 5 + 6 + 9 + 10 = 33 Input : 100 Output : 762 Naive Approach: Find each number up to n whose 2 bits are set. If its 2 bits are set add it to the sum. C/C++ Code // CPP program to find sum
    8 min read
  • Find the largest number smaller than integer N with maximum number of set bits
    Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.I
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences