Maximum AND value of a pair in an array

We are given an array of n positive elements. we need to find the maximum AND value generated by any pair of element from the array. AND is bitwise & operator.

Examples:

Input : arr[] = {4, 8, 12, 16}
Output : Maximum AND value = 8

Input : arr[] = {4, 8, 16, 2}
Output : Maximum AND value = 0

Naive Approach : Basic Approach is same as maximum xor value. We iterate over all the possible pair and calculate the AND value of those all. Pick the largest value among them. Time complexity of this solution is O(n^2).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find maximum XOR value of a pair
#include<bits/stdc++.h>
using namespace std;
  
  
// Function for finding maximum and value pair
int maxAND(int arr[], int n)
{
    int res = 0;
    for (int i=0; i<n; i++)
       for (int j=i+1; j<n; j++)
          res = max(res, arr[i] & arr[j]);
  
    return res;
}
  
// Driver function
int main()
{
    int arr[] = {4, 8, 6, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Maximum AND Value = " << maxAND(arr,n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find maximum 
// XOR value of a pair
import java.util.*;
import java.lang.*;
    
public class GfG{
       
// Function for finding maximum 
// and value pair
static int maxAND(int arr[], int n)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
        res = res > ( arr[i] & arr[j]) ?
              res : ( arr[i] & arr[j]);
   
    return res;
}
   
// driver function
public static void main(String argc[])
{
    int arr[] = {4, 8, 6, 2};
    int n = arr.length;
    System.out.println("Maximum AND Value = " +
                       maxAND(arr,n));
}
}
  
// This code is contributed by Prerna Saini

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to find maximum XOR
# value of a pair
  
# Function for finding maximum and value pair
def maxAND(arr, n) :
    res = 0
      
    for i in range(0, n) :
        for j in range(i + 1, n) :
            res = max(res, arr[i] & arr[j])
      
    return res
  
# Driver function
arr = [4, 8, 6, 2]
n = len(arr)
print("Maximum AND Value = ", maxAND(arr,n))
    
# This code is contributed by Nikita Tiwari.  

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find maximum 
// XOR value of a pair
using System;
  
public class GfG
{
      
// Function for finding maximum 
// and value pair
static int maxAND(int []arr, int n)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
        res = res > ( arr[i] & arr[j]) ?
              res : ( arr[i] & arr[j]);
  
    return res;
}
  
// Driver code
public static void Main()
{
    int []arr = {4, 8, 6, 2};
    int n = arr.Length;
    Console.WriteLine("Maximum AND Value = " +
                       maxAND(arr, n));
}
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find maximum
// XOR value of a pair
  
// Function for finding
// maximum and value pair
function maxAND($arr, $n)
{
      
    $res = 0;
    for ($i = 0; $i < $n; $i++)
    for ($j = $i + 1; $j < $n; $j++)
        $res = max($res, $arr[$i] & 
                         $arr[$j]);
  
    return $res;
}
  
    // Driver Code
    $arr = array(4, 8, 6, 2);
    $n = count($arr);
    echo "Maximum AND Value = " , maxAND($arr, $n);
      
// This code is contributed by vt_m.
?>

chevron_right



Output:

Maximum AND Value = 4

Better Approach : Idea is based on properties of AND operator. AND operation of any two bits result in 1 iff both bits are 1. We start from the MSB and check whether we have minimum of two elements of array having set value. If yes then that MSB will be part of our solution and be added to result otherwise we will discard that bit. Similarly, iterating from MSB to LSB (32 to 1) for bit position we can easily check which bit will be part of our solution and will keep adding all such bits to our solution.
Explanation : Lets consider 1st example of {4, 8, 12, 16} :

step 1: Write Bit-representation of each element :
4 = 100, 8 = 1000, 12 = 1100, 16 = 10000
step 2: Check for 1st MSB , pattern = 0 + 16 = 16. Now 5th bit in 16 is set but no other element has 5-bit as set bit so this will not add up to our RES, still RES = 0 and pattern = 0
step 3: Check 4th bit, pattern = 0 + 8 = 8. Now 8 and 12 both have set bit on 4th bit position so that will add up in our solution, RES = 8 and pattern = 8
step 4: Check 3rd bit, pattern = 8 + 4 = 12. Now only 12 has both bits set bit (same as pattern) so we will discard 3rd bit, RES = 8 and pattern = 8
step 5: Check 2nd bit, pattern = 8 + 2 = 10. No element has set bit same as pattern so we will discard 2nd bit, RES = 8 and pattern = 8
step 4: Check 1st bit, pattern = 8 + 1 = 9. No element has set bit same as pattern so we will discard 1st bit, RES = 8 and pattern = 8

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find maximum XOR value of a pair
#include<bits/stdc++.h>
using namespace std;
  
// Utility function to check number of elements
// having set msb as of pattern
int checkBit(int pattern, int arr[], int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr[i]) == pattern)
            count++;
    return count;
}
  
// Function for finding maximum and value pair
int maxAND (int arr[], int n)
{
    int res = 0, count;
  
    // iterate over total of 30bits from msb to lsb
    for (int bit = 31; bit >= 0; bit--)
    {
        // find the count of element having set  msb
        count = checkBit(res | (1 << bit),arr,n);
  
        // if count >= 2 set particular bit in result
        if ( count >= 2 )        
            res |= (1 << bit);        
    }
  
    return res;
}
  
// Driver function
int main()
{
    int arr[] = {4, 8, 6, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Maximum AND Value = " << maxAND(arr,n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find maximum
// XOR value of a pair
import java.util.*;
import java.lang.*;
    
public class GfG{
  
// Utility function to check number of elements
// having set msb as of pattern
static int checkBit(int pattern, int arr[], int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr[i]) == pattern)
            count++;
    return count;
}
   
// Function for finding maximum and value pair
static int maxAND (int arr[], int n)
{
    int res = 0, count;
   
    // iterate over total of 30bits 
    // from msb to lsb
    for (int bit = 31; bit >= 0; bit--)
    {
        // find the count of element
        // having set msb
        count = checkBit(res | (1 << bit), arr, n);
   
        // if count >= 2 set particular 
        // bit in result
        if ( count >= 2 )     
            res |= (1 << bit);     
    }
   
    return res;
}
    
// driver function
public static void main(String argc[])
{
    int arr[] = {4, 8, 6, 2};
    int n = arr.length;
    System.out.println("Maximum AND Value = "
                       maxAND(arr, n));
}
}
  
// This code is contributed by Prerna Saini

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to find maximum XOR 
# value of a pair
  
# Utility function to check number of
# elements having set msb as of pattern
def checkBit(pattern,arr,  n) :
    count = 0
      
    for i in range(0, n) :
        if ((pattern & arr[i]) == pattern) :
            count = count + 1
    return count
  
# Function for finding maximum and 
# value pair
def maxAND (arr,  n) :
    res = 0
      
    # iterate over total of 30bits 
    # from msb to lsb
    for bit in range(31,-1,-1) :
        
        # find the count of element
        # having set  msb
        count = checkBit(res | (1 << bit), arr, n)
   
        # if count >= 2 set particular
        # bit in result
        if ( count >= 2 ) :
            res =res | (1 << bit)
              
    return res
      
   
# Driver function
arr = [4, 8, 6, 2]
n = len(arr)
print("Maximum AND Value = ", maxAND(arr, n))
  
# This code is contributed by Nikita Tiwari

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find maximum
// XOR value of a pair
using System;
  
public class GfG
{
  
// Utility function to check 
// number of elements having
// set msb as of pattern
static int checkBit(int pattern, 
                    int []arr,
                    int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr[i]) == pattern)
            count++;
    return count;
}
  
// Function for finding maximum
// and value pair
static int maxAND (int []arr, int n)
{
    int res = 0, count;
  
    // iterate over total of 30bits 
    // from msb to lsb
    for (int bit = 31; bit >= 0; bit--)
    {
          
        // find the count of element
        // having set msb
        count = checkBit(res | (1 << bit), arr, n);
  
        // if count >= 2 set particular 
        // bit in result
        if (count >= 2)     
            res |= (1 << bit);     
    }
  
    return res;
}
  
// Driver Code
public static void Main()
{
    int []arr = {4, 8, 6, 2};
    int n = arr.Length;
    Console.WriteLine("Maximum AND Value = "
                       maxAND(arr, n));
}
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find maximum 
// XOR value of a pair
  
// Utility function to check 
// number of elements having
// set msb as of pattern
function checkBit($pattern, $arr, $n)
{
    $count = 0;
    for ($i = 0; $i < $n; $i++)
        if (($pattern & $arr[$i]) == $pattern)
            $count++;
    return $count;
}
  
// Function for finding 
// maximum and value pair
function maxAND ($arr, $n)
{
    $res = 0;$count;
  
    // iterate over total of
    // 30bits from msb to lsb
    for ($bit = 31; $bit >= 0; $bit--)
    {
          
        // find the count of element
        // having set msb
        $count = checkBit($res | (1 << $bit), 
                                   $arr, $n);
  
        // if count >= 2 set particular
        // bit in result
        if ( $count >= 2 ) 
            $res |= (1 << $bit); 
    }
  
    return $res;
}
  
    // Driver Code
    $arr = array(4, 8, 6, 2);
    $n = count($arr);
    echo "Maximum AND Value = " , maxAND($arr,$n);
      
// This code is contributed by vt_m.
?>

chevron_right



Output:

Maximum AND Value = 4

Time Complexity : O(n * log(m)) where m is the maximum element from the array and n is the size of the array.



My Personal Notes arrow_drop_up

Discovering ways to develop a plane for soaring career goals

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.



Improved By : vt_m, nidhi_biet, gp6



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.