Saturday, December 28, 2024
Google search engine
HomeData Modelling & AIFind triplets in an array whose AND is maximum

Find triplets in an array whose AND is maximum

Given an array of positive integers of size n. Find the count of the triplets whose AND is maximum and also find that maximum given that i < j < k where i, j, k are the indices of the numbers. 
Assuming that numbers will not be greater than 10^9.

Examples: 

Input : a[] = {1, 2, 3, 4, 5, 6} 
Output : 1 4 
Explanation: Maximum number that can formed is 4 ( 4 & 5 & 6 ) and only 1 triplet is possible.

Input : a[] = {4, 11, 10, 15, 26} 
Output : 4 10 
Explanation: Maximum number that can formed is 10. There are 4 triplets possible – {11, 10, 15}, {11, 10, 26}, {11, 15, 26}, {10, 15, 26}

A naive approach is to use 3 loops and generate all triplets and calculate the maximum number that can be formed and count of such triplets. 
Time Complexity: O(N^3) 

A better approach is to first represent the number in its binary representation and store it in a 2d array. Since the number cannot be greater than 2^32 ( due to the constraints given in the question ), thus it will take at max 32 iterations for each number. We will also take a boolean flag array which will represent all numbers that can be used to make the max triplet. Initially, we set the array to true since every number can be used. 

Let the maximum AND number be X initially zero. 

Now we want to maximize X so we start traversing the 2D table from the index which represents the 32nd bit of the number and we will count the number of 1’s which are present at the 32nd bit of the numbers which are available for the triplets ie whose flags are true. If the count of 1’s is greater than equal to 3 that means there is/are triplets possible to make the ith bit of X set, then we will set the flag of all the numbers whose ith bit is not set and also add the power i to the base 2 to X. Else, if the count is less than 3 then ith of X will be unset and we do not need to change the flags of the numbers since there can be combinations of 1’s and 0’s for that bit. 

We will repeat the above process for every bit in the reverse order that is from 32 till 0th. 
At we will count the number of numbers whose flags are set let that be r. Then for number of triplets we just need to calculate rC3 { r*(r-1)*(r-2)/6 }. 

Implementation

C++




// CPP program to find triplet with maximum
// bitwise AND.
#include "cmath"
#include "cstring"
#include "iostream"
using namespace std;
 
int maxTriplet(int a[], int n)
{
    // Flag Array initially set to true
    // for all numbers
    bool f[n];
    memset(f, true, sizeof(f));
 
    // 2D array for bit representation
    // of all the numbers.
    // Initially all bits are set to 0.
    int bits[n][33];
    memset(bits, 0, sizeof(bits));
 
    for (int i = 0; i < n; ++i) {
        int num = a[i];
        int j = 32;
 
        // Finding bit representation
        // of every number and
        // storing it in bits array.
        while (num) {
 
            // Checking last bit of the number
            if (num & 1) {
                bits[i][j] = 1;
            }
 
            j--;
 
            // Dividing number by 2.
            num >>= 1;
        }
    }
 
    // maximum And number initially 0.
    long long ans = 0;
 
    // Traversing the 2d binary representation.
    // 0th index represents 32th bits
    // while 32th index represents 0th bit.
    for (long long i = 0; i <= 32; ++i) {
        int cnt = 0;
 
        for (int j = 0; j < n; ++j) {
            if (bits[j][i] and f[j]) {
                cnt++;
            }
        }
 
        // If cnt greater than 3 then (32-i)th bits
        // of the number will be set.
        if (cnt >= 3) {
 
            ans += pow(2LL, 32 - i);
 
            // Setting flags of the numbers
            // whose ith bit is not set.
            for (int j = 0; j < n; ++j) {
                if (!bits[j][i]) {
                    f[j] = false;
                }
            }
        }
    }
 
    // Counting the numbers whose flag are true.
    int cnt = 0;
    for (int i = 0; i < n; ++i) {
        if (f[i]) {
            cnt++;
        }
    }
 
    long long NumberOfTriplets =
          (cnt * (cnt - 1) * (cnt - 2)) / 6;
 
    cout << NumberOfTriplets << " " << ans;
}
 
int main(int argc, char const* argv[])
{
    int a[] = { 4, 11, 10, 15, 26 };
    int n = sizeof(a) / sizeof(a[0]);
    maxTriplet(a, n);
    return 0;
}


Java




// Java program to find triplet with maximum
// bitwise AND.
import java.util.Arrays;
 
class GFG {
     
static void maxTriplet(int a[], int n)
{
    // Flag Array initially set to true
    // for all numbers
    boolean []f = new boolean[n];
    Arrays.fill(f, true);
 
    // 2D array for bit representation
    // of all the numbers.
    // Initially all bits are set to 0.
    int bits[][] = new int[n][33];
 
    for (int i = 0; i < n; ++i)
    {
        int num = a[i];
        int j = 32;
 
        // Finding bit representation
        // of every number and
        // storing it in bits array.
        while (num > 0)
        {
            // Checking last bit of the number
            if (num % 2 == 1)
            {
                bits[i][j] = 1;
            }
             
            j--;
 
            // Dividing number by 2.
            num >>= 1;
        }
    }
     
    // maximum And number initially 0.
    long ans = 0;
 
    // Traversing the 2d binary representation.
    // 0th index represents 32th bits
    // while 32th index represents 0th bit.
    for (int i = 0; i <= 32; ++i)
    {
        int cnt = 0;
 
        for (int j = 0; j < n; ++j)
        {
            if (bits[j][i] == 1 & f[j])
            {
                cnt++;
            }
        }
 
        // If cnt greater than 3 then (32-i)th bits
        // of the number will be set.
        if (cnt >= 3) {
 
            ans += Math.pow(2, 32 - i);
 
            // Setting flags of the numbers
            // whose ith bit is not set.
            for (int j = 0; j < n; ++j) {
                if (bits[j][i] != 1) {
                    f[j] = false;
                }
            }
        }
    }
 
    // Counting the numbers whose flag are true.
    int cnt = 0;
    for (int i = 0; i < n; ++i) {
        if (f[i]) {
            cnt++;
        }
    }
 
    long NumberOfTriplets = (cnt * (cnt - 1) * (cnt - 2)) / 6;
 
    System.out.print(NumberOfTriplets + " " + ans);
}
 
// Driver code
public static void main(String[] args) {
int a[] = { 4, 11, 10, 15, 26 };
    int n = a.length;
    maxTriplet(a, n);
     
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 program to find triplet with
# maximum bitwise AND.
def maxTriplet(a, n):
 
    # Flag Array initially set to true
    # for all numbers
    f = [True for i in range(n)]
 
    # 2D array for bit representation
    # of all the numbers.
    # Initially all bits are set to 0.
    bits = [[0 for i in range(33)]
               for i in range(n)]
 
    for i in range(n):
        num = a[i]
        j = 32
 
        # Finding bit representation
        # of every number and
        # storing it in bits array.
        while (num):
 
            # Checking last bit of the number
            if (num & 1) :
                bits[i][j] = 1
             
            j -= 1
 
            # Dividing number by 2.
            num >>= 1
         
    # maximum And number initially 0.
    ans = 0
 
    # Traversing the 2d binary representation.
    # 0th index represents 32th bits
    # while 32th index represents 0th bit.
    for i in range(33):
        cnt = 0
 
        for j in range(n):
            if (bits[j][i] and f[j]):
                cnt += 1
             
        # If cnt greater than 3 then (32-i)th
        # bits of the number will be set.
        if (cnt >= 3):
 
            ans += pow(2, 32 - i)
 
            # Setting flags of the numbers
            # whose ith bit is not set.
            for j in range(n):
                if (bits[j][i] == False) :
                    f[j] = False
 
    # Counting the numbers whose
    # flag are true.
    cnt = 0
    for i in range(n):
        if (f[i]):
            cnt += 1
         
    NumberOfTriplets = (cnt * (cnt - 1) * (cnt - 2)) // 6
    print(NumberOfTriplets, ans)
 
# Driver Code
a = [ 4, 11, 10, 15, 26]
n = len(a)
maxTriplet(a, n)
 
# This code is contributed by Mohit Kumar29


C#




// C# program to find triplet with maximum
// bitwise AND.
using System;
class GFG
{
static void maxTriplet(int []a, int n)
{
    // Flag Array initially set to true
    // for all numbers
    Boolean []f = new Boolean[n];
    for (int i = 0; i < n; ++i)
        f[i] = true;
 
    // 2D array for bit representation
    // of all the numbers.
    // Initially all bits are set to 0.
    int [,]bits = new int[n, 33];
 
    for (int i = 0; i < n; ++i)
    {
        int num = a[i];
        int j = 32;
 
        // Finding bit representation
        // of every number and
        // storing it in bits array.
        while (num > 0)
        {
            // Checking last bit of the number
            if (num % 2 == 1)
            {
                bits[i, j] = 1;
            }
             
            j--;
 
            // Dividing number by 2.
            num >>= 1;
        }
    }
     
    // maximum And number initially 0.
    long ans = 0;
    int cnt;
     
    // Traversing the 2d binary representation.
    // 0th index represents 32th bits
    // while 32th index represents 0th bit.
    for (int i = 0; i <= 32; ++i)
    {
        cnt = 0;
 
        for (int j = 0; j < n; ++j)
        {
            if (bits[j, i] == 1 & f[j])
            {
                cnt++;
            }
        }
 
        // If cnt greater than 3 then (32-i)th bits
        // of the number will be set.
        if (cnt >= 3)
        {
            ans += (long)Math.Pow(2, 32 - i);
 
            // Setting flags of the numbers
            // whose ith bit is not set.
            for (int j = 0; j < n; ++j)
            {
                if (bits[j, i] != 1)
                {
                    f[j] = false;
                }
            }
        }
    }
 
    // Counting the numbers whose flag are true.
    cnt = 0;
    for (int i = 0; i < n; ++i)
    {
        if (f[i])
        {
            cnt++;
        }
    }
 
    long NumberOfTriplets = (cnt * (cnt - 1) *
                            (cnt - 2)) / 6;
 
    Console.Write(NumberOfTriplets + " " + ans);
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 4, 11, 10, 15, 26 };
    int n = a.Length;
    maxTriplet(a, n);
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript program to find triplet with maximum
// bitwise AND.
 
function maxTriplet(a,n)
{
    // Flag Array initially set to true
    // for all numbers
    let f = new Array(n);
    for(let i=0;i<n;i++)
    {
        f[i]=true;
    }
   
    // 2D array for bit representation
    // of all the numbers.
    // Initially all bits are set to 0.
    let bits = new Array(n);
    for(let i=0;i<n;i++)
    {
        bits[i]=new Array(33);
        for(let j=0;j<33;j++)
        {
            bits[i][j]=0;
        }
    }
   
    for (let i = 0; i < n; ++i)
    {
        let num = a[i];
        let j = 32;
   
        // Finding bit representation
        // of every number and
        // storing it in bits array.
        while (num > 0)
        {
            // Checking last bit of the number
            if (num % 2 == 1)
            {
                bits[i][j] = 1;
            }
               
            j--;
   
            // Dividing number by 2.
            num >>= 1;
        }
    }
       
    // maximum And number initially 0.
    let ans = 0;
   
    // Traversing the 2d binary representation.
    // 0th index represents 32th bits
    // while 32th index represents 0th bit.
    for (let i = 0; i <= 32; ++i)
    {
        let cnt = 0;
   
        for (let j = 0; j < n; ++j)
        {
            if (bits[j][i] == 1 & f[j])
            {
                cnt++;
            }
        }
   
        // If cnt greater than 3 then (32-i)th bits
        // of the number will be set.
        if (cnt >= 3) {
   
            ans += Math.pow(2, 32 - i);
   
            // Setting flags of the numbers
            // whose ith bit is not set.
            for (let j = 0; j < n; ++j) {
                if (bits[j][i] != 1) {
                    f[j] = false;
                }
            }
        }
    }
   
    // Counting the numbers whose flag are true.
    let cnt = 0;
    for (let i = 0; i < n; ++i) {
        if (f[i]) {
            cnt++;
        }
    }
   
    let NumberOfTriplets = (cnt * (cnt - 1) * (cnt - 2)) / 6;
   
    document.write(NumberOfTriplets + " " + ans);
}
 
// Driver code
let a=[4, 11, 10, 15, 26];
let n = a.length;
maxTriplet(a, n);
 
 
// This code is contributed by patel2127
</script>


Output

4 10

Time Complexity: O(NlogN) 

Since each number is can be converted to its binary in logN.

Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments