Print pair with maximum AND value in an array | CPP Program to find pair with maximum AND value ; Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } int maxAND ( int arr [ ] , int n ) { int res = 0 , count ; for ( int bit = 31 ; bit >= 0 ; bit -- ) { count = checkBit ( res | ( 1 << bit ) , arr , n ) ; if ( count >= 2 ) res |= ( 1 << bit ) ; } if ( res == 0 ) cout << " Not ▁ Possible STRNEWLINE " ; else { cout << " Pair ▁ = ▁ " ; count = 0 ; for ( int i = 0 ; i < n && count < 2 ; i ++ ) { if ( ( arr [ i ] & res ) == res ) { count ++ ; cout << arr [ i ] << " ▁ " ; } } } return res ; } int main ( ) { int arr [ ] = { 4 , 8 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum AND Value = " << maxAND ( arr , n ) ; return 0 ; }