Maximum Bitwise AND value of subsequence of length K

Given an array a of size N and an integer K. The task is to find the maximum bitwise and value of elements of any subsequence of length K.

Note: a[i] <= 109

Examples:



Input: a[] = {10, 20, 15, 4, 14}, K = 4
Output: 4
{20, 15, 4, 14} is the subsequence with highest ‘&’ value.

Input: a[] = {255, 127, 31, 5, 24, 37, 15}, K = 5
Output: 8

Naive Approach: A naive approach is to recursively find the bitwise and value of all subsequences of length K and the maximum among all of them will be the answer.

Efficient Approach: An efficient approach is to solve it using bit properties. Below are the steps to solve the problem:

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the sum of
// the addition of all possible subsets.
#include <bits/stdc++.h>
using namespace std;
  
// Function to perform step-1
vector<int> findSubset(vector<int>& temp, int& last, int k)
{
    vector<int> ans;
  
    // Iterate from left till 0
    // till we get a bit set of K numbers
    for (int i = last; i >= 0; i--) {
        int cnt = 0;
  
        // Count the numbers whose
        // i-th bit is set
        for (auto it : temp) {
            int bit = it & (1 << i);
            if (bit > 0)
                cnt++;
        }
  
        // If the array has numbers>=k
        // whose i-th bit is set
        if (cnt >= k) {
            for (auto it : temp) {
                int bit = it & (1 << i);
                if (bit > 0)
                    ans.push_back(it);
            }
  
            // Update last
            last = i - 1;
  
            // Return the new set of numbers
            return ans;
        }
    }
  
    return ans;
}
  
// Function to find the maximum '&' value
// of K elements in subsequence
int findMaxiumAnd(int a[], int n, int k)
{
    int last = 31;
    // Temporary arrays
    vector<int> temp1, temp2;
  
    // Initially temp = arr
    for (int i = 0; i < n; i++) {
        temp2.push_back(a[i]);
    }
  
    // Iterate till we have >=K elements
    while ((int)temp2.size() >= k) {
  
        // Temp array
        temp1 = temp2;
  
        // Find new temp array if
        // K elements are there
        temp2 = findSubset(temp2, last, k);
    }
  
    // Find the & value
    int ans = temp1[0];
    for (int i = 0; i < k; i++)
        ans = ans & temp1[i];
  
    return ans;
}
  
// Driver Code
int main()
{
    int a[] = { 255, 127, 31, 5, 24, 37, 15 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 4;
  
    cout << findMaxiumAnd(a, n, k);
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the sum of
// the addition of all possible subsets.
import java.util.*;
class GFG
{
static int last;
  
// Function to perform step-1
static Vector<Integer> 
       findSubset(Vector<Integer> temp, int k)
{
    Vector<Integer> ans = new Vector<Integer>();
  
    // Iterate from left till 0
    // till we get a bit set of K numbers
    for (int i = last; i >= 0; i--)
    {
        int cnt = 0;
  
        // Count the numbers whose
        // i-th bit is set
        for (Integer it : temp)
        {
            int bit = it & (1 << i);
            if (bit > 0)
                cnt++;
        }
  
        // If the array has numbers>=k
        // whose i-th bit is set
        if (cnt >= k) 
        {
            for (Integer it : temp) 
            {
                int bit = it & (1 << i);
                if (bit > 0)
                    ans.add(it);
            }
  
            // Update last
            last = i - 1;
  
            // Return the new set of numbers
            return ans;
        }
    }
    return ans;
}
  
// Function to find the maximum '&' value
// of K elements in subsequence
static int findMaxiumAnd(int a[], int n, int k)
{
    last = 31;
      
    // Temporary arrays
    Vector<Integer> temp1 = new Vector<Integer>();
    Vector<Integer> temp2 = new Vector<Integer>();;
  
    // Initially temp = arr
    for (int i = 0; i < n; i++) 
    {
        temp2.add(a[i]);
    }
  
    // Iterate till we have >=K elements
    while ((int)temp2.size() >= k) 
    {
  
        // Temp array
        temp1 = temp2;
  
        // Find new temp array if
        // K elements are there
        temp2 = findSubset(temp2, k);
    }
  
    // Find the & value
    int ans = temp1.get(0);
    for (int i = 0; i < k; i++)
        ans = ans & temp1.get(i);
  
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int a[] = { 255, 127, 31, 5, 24, 37, 15 };
    int n = a.length;
    int k = 4;
  
    System.out.println(findMaxiumAnd(a, n, k));
}
}
  
// This code is contributed by 29AjayKumar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the sum of
# the addition of all possible subsets.
last = 31
  
# Function to perform step-1
def findSubset(temp, k):
    global last
    ans = []
  
    # Iterate from left till 0
    # till we get a bit set of K numbers
    for i in range(last, -1, -1):
        cnt = 0
  
        # Count the numbers whose
        # i-th bit is set
        for it in temp:
            bit = it & (1 << i)
            if (bit > 0):
                cnt += 1
  
        # If the array has numbers>=k
        # whose i-th bit is set
        if (cnt >= k):
            for it in temp:
                bit = it & (1 << i)
                if (bit > 0):
                    ans.append(it)
  
            # Update last
            last = i - 1
  
            # Return the new set of numbers
            return ans
  
    return ans
  
# Function to find the maximum '&' value
# of K elements in subsequence
def findMaxiumAnd(a, n, k):
    global last
  
    # Temporary arrays
    temp1, temp2, = [], []
  
    # Initially temp = arr
    for i in range(n):
        temp2.append(a[i])
  
    # Iterate till we have >=K elements
    while len(temp2) >= k:
  
        # Temp array
        temp1 = temp2
  
        # Find new temp array if
        # K elements are there
        temp2 = findSubset(temp2, k)
  
    # Find the & value
    ans = temp1[0]
    for i in range(k):
        ans = ans & temp1[i]
  
    return ans
  
# Driver Code
a = [255, 127, 31, 5, 24, 37, 15]
n = len(a)
k = 4
  
print(findMaxiumAnd(a, n, k))
  
# This code is contributed by Mohit Kumar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the sum of
// the addition of all possible subsets.
using System;
using System.Collections.Generic;
  
class GFG
{
static int last;
  
// Function to perform step-1
static List<int>findSubset(List<int> temp, int k)
{
    List<int> ans = new List<int>();
  
    // Iterate from left till 0
    // till we get a bit set of K numbers
    for (int i = last; i >= 0; i--)
    {
        int cnt = 0;
  
        // Count the numbers whose
        // i-th bit is set
        foreach (int it in temp)
        {
            int bit = it & (1 << i);
            if (bit > 0)
                cnt++;
        }
  
        // If the array has numbers>=k
        // whose i-th bit is set
        if (cnt >= k) 
        {
            foreach (int it in temp) 
            {
                int bit = it & (1 << i);
                if (bit > 0)
                    ans.Add(it);
            }
  
            // Update last
            last = i - 1;
  
            // Return the new set of numbers
            return ans;
        }
    }
    return ans;
}
  
// Function to find the maximum '&' value
// of K elements in subsequence
static int findMaxiumAnd(int []a, int n, int k)
{
    last = 31;
      
    // Temporary arrays
    List<int> temp1 = new List<int>();
    List<int> temp2 = new List<int>();;
  
    // Initially temp = arr
    for (int i = 0; i < n; i++) 
    {
        temp2.Add(a[i]);
    }
  
    // Iterate till we have >=K elements
    while ((int)temp2.Count >= k) 
    {
  
        // Temp array
        temp1 = temp2;
  
        // Find new temp array if
        // K elements are there
        temp2 = findSubset(temp2, k);
    }
  
    // Find the & value
    int ans = temp1[0];
    for (int i = 0; i < k; i++)
        ans = ans & temp1[i];
  
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []a = { 255, 127, 31, 5, 24, 37, 15 };
    int n = a.Length;
    int k = 4;
  
    Console.WriteLine(findMaxiumAnd(a, n, k));
}
}
  
// This code is contributed by Rajput-Ji
chevron_right

Output:
24



Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :