text: Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array | C ++ Program to implement the above approach ; Function to maximize the value for the given function and the array elements ; Vector array to maintain which bit is set for which integer in the given array by saving index of that integer ; Check if j - th bit is set for i - th integer ; Push the index of that integer in setBit [ j ] ; Find the element having highest significant set bit unset in other elements ; Place that integer at 0 - th index ; Store the maximum AND value ; Return the answer ; Driver Code ; Function call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define size_int  32 NEW_LINE int functionMax ( int arr [ ] , int n ) { vector < int > setBit [ 32 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < size_int ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) setBit [ j ] . push_back ( i ) ; } } for ( int i = size_int ; i >= 0 ; i -- ) { if ( setBit [ i ] . size ( ) == 1 ) { swap ( arr [ 0 ] , arr [ setBit [ i ] [ 0 ] ] ) ; break ; } } int maxAnd = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { maxAnd = maxAnd & ( ~ arr [ i ] ) ; } return maxAnd ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 16 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << functionMax ( arr , n ) ; return 0 ; }