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 ; List 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: using System ; using System . Collections . Generic ; class GFG { static readonly int size_int = 32 ; static int functionMax ( int [ ] arr , int n ) { List < int > [ ] setBit = new List < int > [ 32 + 1 ] ; for ( int i = 0 ; i < setBit . Length ; i ++ ) setBit [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < size_int ; j ++ ) { if ( ( arr [ i ] & ( 1 << j ) ) > 0 ) setBit [ j ] . Add ( i ) ; } } for ( int i = size_int ; i >= 0 ; i -- ) { if ( setBit [ i ] . Count == 1 ) { swap ( arr , 0 , setBit [ i ] [ 0 ] ) ; break ; } } int maxAnd = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { maxAnd = maxAnd & ( ~ arr [ i ] ) ; } return maxAnd ; } static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 8 , 16 } ; int n = arr . Length ; Console . Write ( functionMax ( arr , n ) ) ; } }