Open In App

Maximum AND value of a pair in an array

Improve
Improve
Like Article
Like
Save
Share
Report

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: 8
Explanation: 8 AND12 will give us the maximum value 8

Input: arr1[] = {4, 8, 16, 2}
Output: 0

Recommended Practice

The idea is to iterate over all the possible pairs and calculate the AND value of those all. and pick the largest value among them.

Follow the steps mentioned below to implement the approach:

  • Declare a variable res to store the final answer.
  • Create a nested loop and traverse all pairs, storing the maximum value of AND of a pair on res.
  • Return res.

Below is the implementation of the above approach:

C++




// 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;
}


Java




// Java Program to find maximum
// XOR value of a pair
import java.lang.*;
import java.util.*;
 
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


Python3




# 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.


C#




// 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.


Javascript




<script>
 
 
// Javascript Program to find maximum XOR value of a pair
 
// Function for finding maximum and value pair
function 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 function
var arr = [4, 8, 6, 2];
var n = arr.length;
document.write( "Maximum AND Value = " + maxAND(arr,n));
 
</script>


PHP




<?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.
?>


Output

Maximum AND Value = 4

Time Complexity: O(N2)
Auxiliary Space: O(1)

Maximum AND value of a pair in an array using Bit Manipulation

The idea is based on the property of AND operator. AND operation of any two bits results in 1 if both bits are 1. We start from the MSB and check whether we have a 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. 

Illustration:
Below is the illustration of example arr[] = { 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 means we have 10000 as our pattern in binary equivalent. 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 means we have 1000 as our pattern in binary equivalent. 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  i.e. RES = 1000 and pattern = 1000.
  • step 4: Check 3rd bit, pattern = 8 + 4 = 12.  i.e. after adding 3rd bit our pattern becomes 1100 .when we check how many no. in the array have this pattern we find now only 12 satisfies it less two numbers .  so we will discard 3rd bit, RES = 8 (1000)and pattern = 8(1000) 
  • step 5: Check 2nd bit, pattern = 8 + 2 = 10 , after adding 2nd bit our pattern becomes 1010 .when we check how many no. in the array have this pattern we find no element have this pattern inside it ie. No element has set bit same as pattern so we will discard 2nd bit, RES = 8 (1000) and pattern = 8(1000). 
  • step 4: Check 1st bit, pattern = 8 + 1 = 9 ie.  i.e. after adding 3rd bit our pattern becomes 1001. No element has set bit same as pattern so we will discard 1st bit, RES = 8(1000) and pattern = 8(1000). 

Follow the steps mentioned below to implement the approach:

  • Create a variable res to store the final answer.
  • Traverse a loop from 31 to 0 to see if there are more than one elements in the array whose AND with res equals res if we add the current bit to res and keep updating res.
  • Return res as the final answer

Below is the implementation of the above approach:

C++




// 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 32bits from msb to lsb
    for (int bit = 31; bit >= 0; bit--) {
        // find the count of element having same pattern as
        // obtained by adding bits on every iteration.
        count = checkBit(res | (1 << bit), arr, n);
 
        // if count >= 2 set particular bit in result
        if (count >= 2)
            res = res | (1 << bit); // this is the pattern
                                    // we continued
    }
 
    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;
}


Java




// Java Program to find maximum
// XOR value of a pair
import java.lang.*;
import java.util.*;
 
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 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 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


Python3




# 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 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 function
arr = [4, 8, 6, 2]
n = len(arr)
print("Maximum AND Value = ", maxAND(arr, n))
 
# This code is contributed by Nikita Tiwari


C#




// 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 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 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.


Javascript




<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>


PHP




<?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
    // 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.
?>


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.
Auxiliary Space: O(1)



Last Updated : 12 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads