Find triplets in an array whose AND is maximum
Last Updated :
17 Apr, 2023
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>
Time Complexity: O(NlogN)
Since each number is can be converted to its binary in logN.
Auxiliary Space: O(N)
Similar Reads
Find pair with maximum ratio in an Array
Given an array arr[], the task is to find the maximum ratio pair in the array.Examples: Input: arr[] = { 15, 10, 3 } Output: 5 Explanation: Maximum ratio pair will be - \frac{15}{3} = 5 Input: arr[] = { 15, 10, 3, 2 } Output: 7.5 Explanation: Maximum ratio pair will be - \frac{15}{2} = 7.5 Approach:
8 min read
Find pair with maximum GCD in an array
We are given an array of positive integers. Find the pair in array with maximum GCD.Examples: Input : arr[] : { 1 2 3 4 5 }Output : 2Explanation : Pair {2, 4} has GCD 2 which is highest. Other pairs have a GCD of 1.Input : arr[] : { 2 3 4 8 8 11 12 }Output : 8Explanation : Pair {8, 8} has GCD 8 whic
15+ min read
Print pair with maximum AND value in an array
Given an array of n positive elements, find the maximum AND value and the pair of elements generating the maximum AND value from the array. AND is bitwise & operator. Examples: Input : arr[] = {4, 8, 12, 16} Output : Pair = 8, 12 Maximum AND value = 8 Input : arr[] = {4, 8, 16, 2} Output : Pair
9 min read
Find a pair with maximum product in array of Integers
Given an array with both +ive and -ive integers, return a pair with the highest product. Examples : Input: arr[] = {1, 4, 3, 6, 7, 0} Output: {6,7} Input: arr[] = {-1, -3, -4, 2, 0, -5} Output: {-4,-5} Recommended PracticeMaximum product of two numbersTry It! A Simple Solution is to consider every p
15+ min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array.Input: arr[] = {3, 2, 2, 2}Output: 3Expla
7 min read
Find the element having maximum premutiples in the array
Given an array arr[], the task is to find the element which has the maximum number of pre-multiples present in the set. For any index i, pre-multiple is the number that is multiple of i and is present before the ith index of the array. Also, print the count of maximum multiples of that element in th
8 min read
Find maximum in an array without using Relational Operators
Given an array A[] of non-negative integers, find the maximum in the array without using Relational Operator. Examples: Input : A[] = {2, 3, 1, 4, 5}Output : 5Input : A[] = {23, 17, 93}Output : 93We use repeated subtraction to find out the maximum. To find maximum between two numbers, we take a vari
9 min read
Maximum AND value of a pair in an array
Given an array of N positive elements, the task is to find the maximum AND value generated by any pair of elements from the array. Examples: Input: arr1[] = {16, 12, 8, 4}Output: 8Explanation: 8 AND12 will give us the maximum value 8 Input: arr1[] = {4, 8, 16, 2}Output: 0 Recommended PracticeMaximum
12 min read
Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
Given an array of positive integers of size n. Find the maximum sum of triplet( ai + aj + ak ) such that 0 <= i < j < k < n and ai < aj < ak. Input: a[] = 2 5 3 1 4 9Output: 16Explanation:All possible triplets are:-2 3 4 => sum = 92 5 9 => sum = 162 3 9 => sum = 143 4 9 =
11 min read
Find a pair (n,r) in an integer array such that value of nPr is maximum
Given an array of non-negative integers arr[], the task is to find a pair (n, r) such that nPr is the maximum possible and r ⤠n. nPr = n! / (n - r)! Examples: Input: arr[] = {5, 2, 3, 4, 1} Output: n = 5 and r = 4 5P4 = 5! / (5 - 4)! = 120, which is the maximum possible. Input: arr[] = {0, 2, 3, 4,
9 min read