![]() |
VOOZH | about |
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:8AND12 will give us the maximum value 8Input: arr1[] = {4, 8, 16, 2}
Output: 0
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:
Below is the implementation of the above approach:
Maximum AND Value = 4
Time Complexity: O(N2)
Auxiliary Space: O(1)
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.
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:
Below is the implementation of the above approach:
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)