Maximum AND value of a pair in an array - GeeksforGeeks

09 May, 2022
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++
Java
Python3
C#
PHP
Javascript
// CPP Program to find maximum XOR value of a pair#include<bits/stdc++.h>using namespace std;  // Function for finding maximum and value pairint 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 functionint main(){    int arr[] = {4, 8, 6, 2};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Maximum AND Value = " << maxAND(arr,n);    return 0;}
// Java Program to find maximum// XOR value of a pairimport java.util.*;import java.lang.*;   public class GfG{      // Function for finding maximum// and value pairstatic 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 functionpublic 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
# Python3 Program to find maximum XOR# value of a pair # Function for finding maximum and value pairdef 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 functionarr = [4, 8, 6, 2]n = len(arr)print("Maximum AND Value = ", maxAND(arr,n))   # This code is contributed by Nikita Tiwari. 
// C# Program to find maximum// XOR value of a pairusing System; public class GfG{     // Function for finding maximum// and value pairstatic 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 codepublic 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.
<?php// PHP Program to find maximum// XOR value of a pair // Function for finding// maximum and value pairfunction 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.?>
<script>  // Javascript Program to find maximum XOR value of a pair // Function for finding maximum and value pairfunction maxAND(arr, n){    var res = 0;    for (var i=0; i<n; i++)       for (var j=i+1; j<n; j++)          res = Math.max(res, arr[i] & arr[j]);     return res;} // Driver functionvar arr = [4, 8, 6, 2];var n = arr.length;document.write( "Maximum AND Value = " + maxAND(arr,n)); </script>
Output: 
Maximum AND Value = 4
Better Approach : Idea is based on properties of AND operator. AND operation of any two bits result in 1 if 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++
Java
Python3
C#
PHP
Javascript
// 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 patternint 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 pairint maxAND (int arr[], int n){    int res = 0, count;     // iterate over total of 32bits 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 functionint main(){    int arr[] = {4, 8, 6, 2};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Maximum AND Value = " << maxAND(arr,n);    return 0;}
// Java Program to find maximum// XOR value of a pairimport java.util.*;import java.lang.*;   public class GfG{ // Utility function to check number of elements// having set msb as of patternstatic 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 pairstatic int maxAND (int arr[], int n){    int res = 0, count;      // iterate over total of 32bits    // 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 functionpublic 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
# Python3 Program to find maximum XOR# value of a pair # Utility function to check number of# elements having set msb as of patterndef 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 pairdef maxAND (arr,  n) :    res = 0         # iterate over total of 32bits    # 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 functionarr = [4, 8, 6, 2]n = len(arr)print("Maximum AND Value = ", maxAND(arr, n)) # This code is contributed by Nikita Tiwari
// C# Program to find maximum// XOR value of a pairusing System; public class GfG{ // Utility function to check// number of elements having// set msb as of patternstatic 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 pairstatic int maxAND (int []arr, int n){    int res = 0, count;     // iterate over total of 32bits    // 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 Codepublic 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.
<?php// PHP Program to find maximum// XOR value of a pair // Utility function to check// number of elements having// set msb as of patternfunction 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 pairfunction maxAND ($arr, $n){    $res = 0;$count;     // iterate over total of    // 32bits 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.?>
<script>    // Javascript 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)    {        let count = 0;        for (let i = 0; i < n; i++)            if ((pattern & arr[i]) == pattern)                count++;        return count;    }     // Function for finding maximum    // and value pair    function maxAND (arr, n)    {        let res = 0, count;         // iterate over total of 32bits        // from msb to lsb        for (let 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;    }         let arr = [4, 8, 6, 2];    let n = arr.length;    document.write("Maximum AND Value = " + maxAND(arr, n));         // This code is contributed by divyesh072019.</script>
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. 
vt_m
nidhi_biet
gp6
itsok
divyesh072019
yrk9421
surinderdawra388
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?