Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array | Java 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
import java . util . * ; class GFG { static final int size_int = 32 ; static int functionMax ( int arr [ ] , int n ) { Vector < Integer > [ ] setBit = new Vector [ 32 + 1 ] ; for ( int i = 0 ; i < setBit . length ; i ++ ) setBit [ i ] = new Vector < Integer > ( ) ; 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 ] . size ( ) == 1 ) { swap ( arr , 0 , setBit [ i ] . get ( 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 ; System . out . print ( functionMax ( arr , n ) ) ; } }