https://www.geeksforgeeks.org/maximum-value-pair-array/
- we can also solve use bit trie
https://www.geeksforgeeks.org/print-pair-with-maximum-and-value-in-an-array/
Print pair with maximum AND value 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
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. Similary, 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.
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
https://www.geeksforgeeks.org/print-pair-with-maximum-and-value-in-an-array/
Print pair with maximum AND value in an array
Finding Maximum AND value is same as Maximum AND value in an array. Our task is to find the pair of elements resulting in obtained AND value. For finding the elements, simply traverse the whole array and find the AND value of each element with the obtained maximum AND value (result) and if arr[i] & result == result , that means arr[i] is the element which will generate maximum AND value. Also, in the case if maximum AND value (result) is zero then we should print “Not possible” in that case.