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
  • Data Structures
  • Array
  • String
  • Linked List
  • Stack
  • Queue
  • Tree
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Graph
  • Trie
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • AVL Tree
  • Red-Black Tree
  • Advanced Data Structures
Open In App
Next Article:
Maximize count of array elements required to obtain given sum
Next article icon

Maximize total set bits of elements in N sized Array with sum M

Last Updated : 07 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M.

Examples:

Input: N = 1, M = 15
Output: 4
Explanation: Since N =1, 15 is the only possible solution. 
The binary representation of 15 is (1111)2 which has 4 set bits.

Input: N = 2, M = 11
Output: 4
Explanation: There can be various options for the vector of size 2 and sum 11.
For example: [1, 10] this will give the set bits as 1 + 2 = 3 
as their binary representations are 1 and 1010 respectively.
Similarly [2, 9] and [3, 8] will also give 3 set bits 
as their binary representations are [10, 1001] and [11, 1000] respectively.
For [4, 7] the set bits will be maximum as 
4 is represented by 100 and 7 is represented by 111.
So the total count of set bits = 1 + 3 =4.
Similarly [5, 6] is also a possible solution which gives sum of set bits 4.
For any other options the sum of set bits is always less than 4. 
Hence the maximum number of set bits achieved is 4.

 

Approach: This problem can be solved by the concept of parity and greedy approach based on the following idea:

To maximize the set bit it is optimal to choose as small numbers as possible and set as many bits in each position as possible.

  • Put as many 1s as feasible at the current bit for each bit from lowest to highest. 
  • However, if the parity of M and N differs, we won't be able to put N 1s on that bit since we won't be able to achieve M as the sum no matter how we set the upper bits. 
  • Hence we find out the minimum of N and M (say cur) and then compare the parity of cur and M. 
    If their parity is different we decrease the cur value by 1 to match the parity of M and set that many bits to 1.

Then adjust the sum M, by dividing it by 2 (For easy calculation in next step. We will only need to check the rightmost position and each set bit will contribute 1 to the sum) and repeat this till M becomes 0.

Follow the below illustration for a better understanding:

Illustration:

Consider N = 2 and M = 11.

1st Step:
        => Minimum of 2 and 11 = 2. So cur = 2
        => cur is even and M is odd. Decrease cur by 1. So cur = 2 - 1 = 1.
        => Set 1 bit. So, M = 10, ans = 1.
        => Change M = M/2 = 

2nd Step:
        => Minimum of 2 and 5 = 2. So cur = 2
        => cur is even and M is odd. Decrease cur by 1. So cur = 2 - 1 = 1.
        => Set 1 bits. So, M = 5 - 1 = 4, ans = 1 + 1 = 2.
        => Set M = 4/2 = 2.

3rd Step:
        => Minimum of 2 and 2 = 2. So cur = 2
        => cur is even and M is also even.
        => Set 2 bits. So, M = 2 - 2 = 0, ans = 2 + 2 = 4.
        => Set M = 0/2 = 0.

Follow the below steps to implement the approach:

  • Initialize variables to store minimum in each step and the answer.
  • Iterate a loop till M is greater than 0:
    • Find the minimum of M and N.
    • Find the number of bits to be set using the above observation.
    • Adjust the M accordingly as mentioned above.
    • Add the count of bits set in this stage.
  • At the end return the total count of bits as the required answer.

Below is the implementation of the above approach:

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to find the maximum possible set bits // for an array of size n and sum of elements s int maximizeSetBits(int n, int s) {     int ans = 0;      // Condition for loop till s becomes 0     while (s) {         int cur = min(s, n);          // If parity is different         // some higher bit will be         // set in the next steps         // to achieve sum s         if ((cur % 2) != (s % 2)) {              // Decreasing the cur variable.             cur--;         }          // Updating the ans and sum respectively         ans += cur;         s = (s - cur) / 2;     }      // Return the maximum possible set bit     return ans; } // Driver code int main() {     int N = 2, M = 11;      // Function call     cout << maximizeSetBits(N, M);     return 0; } 
Java
// Java code to implement the approach public class GFG {    // Function to find the maximum possible set bits   // for an array of size n and sum of elements s   static int maximizeSetBits(int n, int s)   {     int ans = 0;      // Condition for loop till s becomes 0     while (s != 0) {       int cur = Math.min(s, n);        // If parity is different       // some higher bit will be       // set in the next steps       // to achieve sum s       if ((cur % 2) != (s % 2)) {          // Decreasing the cur variable.         cur--;       }        // Updating the ans and sum respectively       ans += cur;       s = (s - cur) / 2;     }      // Return the maximum possible set bit     return ans;   }      // Driver code   public static void main (String[] args)   {     int N = 2, M = 11;      // Function call     System.out.println(maximizeSetBits(N, M));   }  }  // This code is contributed by AnkThon 
Python3
# Python3 program to implement the approach  # Function to find the maximum possible set bits # for an array of size n and sum of elements s def maximizeSetBits(n, s):     ans = 0      # Condition for loop till s becomes 0     while s:         cur = min(s, n)          # If parity is different         # some higher bit will be         # set in the next steps         # to achieve sum s         if (cur % 2) != (s % 2):              # Decreasing the cur variable.             cur -= 1          # Updating the ans and sum respectively         ans += cur         s = (s - cur) // 2      # Return the maximum possible set bit     return ans  # Driver code N, M = 2, 11  # Function call print(maximizeSetBits(N, M))      # This code is contributed by phasing17 
C#
// C# code to implement the approach using System; public class GFG {    // Function to find the maximum possible set bits   // for an array of size n and sum of elements s   static int maximizeSetBits(int n, int s)   {     int ans = 0;      // Condition for loop till s becomes 0     while (s != 0) {       int cur = Math.Min(s, n);        // If parity is different       // some higher bit will be       // set in the next steps       // to achieve sum s       if ((cur % 2) != (s % 2)) {          // Decreasing the cur variable.         cur--;       }        // Updating the ans and sum respectively       ans += cur;       s = (s - cur) / 2;     }      // Return the maximum possible set bit     return ans;   }    // Driver code   public static void Main (string[] args)   {     int N = 2, M = 11;      // Function call     Console.WriteLine(maximizeSetBits(N, M));   }  }  // This code is contributed by AnkThon 
JavaScript
<script>  // Function to find the maximum possible set bits // for an array of size n and sum of elements s function maximizeSetBits(n, s) {     let ans = 0;      // Condition for loop till s becomes 0     while (s) {         let cur = Math.min(s, n);          // If parity is different         // some higher bit will be         // set in the next steps         // to achieve sum s         if ((cur % 2) != (s % 2)) {              // Decreasing the cur variable.             cur--;         }          // Updating the ans and sum respectively         ans += cur;         s = (s - cur) / 2;     }      // Return the maximum possible set bit     return ans; } // Driver code      let N = 2;     let M = 11;      // Function call     document.write(maximizeSetBits(N, M));          // This code is contributed by satwak4409.     </script> 

Output
4

Time Complexity: O(log M)
Auxiliary Space: O(1)


Next Article
Maximize count of array elements required to obtain given sum

R

rayush2010
Improve
Article Tags :
  • Data Structures
  • DSA
Practice Tags :
  • Data Structures

Similar Reads

  • Maximize sum of chosen Array elements with value at most M
    Given an array arr[] of N positive numbers and an integer M. The task is to maximize the value of M by adding array elements when arr[i] ≤ M. Note: Any array element can be added at most once. Examples: Input: arr[] = {3, 9, 19, 5, 21}, M = 10Output: 67Explanation: One way to getthe value isM > 3
    4 min read
  • Maximize the minimum array element by M subarray increments of size S
    Given an array arr[] of N integers and two integers S and M, the task is to maximize the minimum array element by incrementing any subarray of size S by 1, M number of times. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, S = 2, M = 3Output: 3Explanation:Below are the operations performed:Operation 1:
    10 min read
  • Maximize count of array elements required to obtain given sum
    Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1. Examples: Input: arr[] =
    8 min read
  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Find element with the maximum set bits in an array
    Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
    5 min read
  • Count of N-size maximum sum Arrays with elements in range [0, 2^K – 1] and Bitwise AND equal to 0
    Given two positive integers N and K, the task is to find the number of arrays of size N such that each array element lies over the range [0, 2K - 1] with the maximum sum of array element having Bitwise AND of all array elements 0. Examples: Input: N = 2 K = 2Output: 4Explanation:The possible arrays
    5 min read
  • Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array
    Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible wa
    15 min read
  • Reduce given Array to 0 by maximising sum of chosen elements
    Given an array arr[] containing N positive integers, the task is to maximize the array sum when after every sum operation all the remaining array elements decrease by 1. Note: The value of an array element does not go below 0. Examples: Input: arr[] = {6, 2, 4, 5} Output: 12 Explanation: Add 6 initi
    9 min read
  • Generate an Array such with elements maximized through swapping bits
    Given an array arr[], the task is to generate a modified array such that all its elements are maximized by swapping of bits.Examples: Input: arr[] = {10, 15} Output: 12, 15 Explanation: Binary representation of (10)10 = (1010)2. Swap the second and third bit to get the binary representation as (1100
    6 min read
  • Maximize the sum of modulus with every Array element
    Given an array A[] consisting of N positive integers, the task is to find the maximum possible value of: F(M) = M % A[0] + M % A[1] + .... + M % A[N -1] where M can be any integer value Examples: Input: arr[] = {3, 4, 6} Output: 10 Explanation: The maximum sum occurs for M = 11. (11 % 3) + (11 % 4)
    4 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