Skip to content
Related Articles

Related Articles

Smallest element with K set bits such that sum of Bitwise AND of each array element with K is maximum
  • Last Updated : 13 Apr, 2021

Given an array arr[] consisting of N integers and integer K, the task is to find the smallest integer X with exactly K set bits such that the sum of Bitwise AND of X with every array element arr[i] is maximum.

Examples:

Input: arr[] = {3, 4, 5, 1}, K = 1
Output: 4
Explanation: Consider the value of X as 4. Then, the sum of Bitwise AND of X and array elements = 4 & 3 + 4 & 4 + 4 & 5 + 4 & 1 = 0 + 4 + 4 + 0 = 8, which is maximum.

Input: arr[] = {1, 3, 4, 5, 2, 5}, K = 2
Output: 5

 

Approach: The given problem can be solved by using the Greedy Approach. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Comparator function to sort the
// vector of pairs
bool comp(pair<int, int>& a,
          pair<int, int>& b)
{
    // If the second is not the same
    // then sort in decreasing order
    if (a.second != b.second)
        return a.second > b.second;
 
    // Otherwise
    return a.first < b.first;
}
 
// Function to find the value of X
// such that Bitwise AND of all array
// elements with X is maximum
int maximizeSum(int arr[], int n, int k)
{
    // Stores the count of set bit at
    // each position
    vector<int> cnt(30, 0);
 
    // Stores the resultant value of X
    int X = 0;
 
    // Calculate the count of set bits
    // at each position
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 30; j++) {
 
            // If the jth bit is set
            if (arr[i] & (1 << j))
                cnt[j]++;
        }
    }
 
    // Stores the contribution
    // of each set bit
    vector<pair<int, int> > v;
 
    // Store all bit and amount of
    // contribution
    for (int i = 0; i < 30; i++) {
 
        // Find the total contribution
        int gain = cnt[i] * (1 << i);
        v.push_back({ i, gain });
    }
 
    // Sort V[] in decreasing
    // order of second parameter
    sort(v.begin(), v.end(), comp);
 
    // Choose exaclty K set bits
    for (int i = 0; i < k; i++) {
        X |= (1 << v[i].first);
    }
 
    // Print the answer
    cout << X;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 4, 5, 1 };
    int K = 1;
    int N = sizeof(arr) / sizeof(arr[0]);
    maximizeSum(arr, N, K);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the value of X
// such that Bitwise AND of all array
// elements with X is maximum
static void maximizeSum(int arr[], int n, int k)
{
     
    // Stores the count of set bit at
    // each position
    int cnt[] = new int[30];
 
    // Stores the resultant value of X
    int X = 0;
 
    // Calculate the count of set bits
    // at each position
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < 30; j++)
        {
             
            // If the jth bit is set
            if ((arr[i] & (1 << j)) != 0)
                cnt[j]++;
        }
    }
 
    // Stores the contribution
    // of each set bit
    ArrayList<int[]> v = new ArrayList<>();
 
    // Store all bit and amount of
    // contribution
    for(int i = 0; i < 30; i++)
    {
         
        // Find the total contribution
        int gain = cnt[i] * (1 << i);
        v.add(new int[] { i, gain });
    }
 
    // Sort V[] in decreasing
    // order of second parameter
    Collections.sort(v, (a, b) -> {
         
        // If the second is not the same
        // then sort in decreasing order
        if (a[1] != b[1])
            return b[1] - a[1];
 
        // Otherwise
        return a[0] - b[0];
    });
 
    // Choose exaclty K set bits
    for(int i = 0; i < k; i++)
    {
        X |= (1 << v.get(i)[0]);
    }
 
    // Print the answer
    System.out.println(X);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 4, 5, 1 };
    int K = 1;
    int N = arr.length;
     
    maximizeSum(arr, N, K);
}
}
 
// This code is contributed by Kingash
Output: 
4

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :