Maximum and minimum sum of Bitwise XOR of pairs from an array | Java code of above approach ; Function to find the required sum ; Keeps the track of the visited array elements ; Stores the result ; Keeps count of visited elements ; Traverse the vector , V ; If n elements are visited , break out of the loop ; Store the pair ( i , j ) and their Bitwise XOR ; If i and j both are unvisited ; Add xorResult to res and mark i and j as visited ; Increment count by 2 ; Return the result ; Function to find the maximum and minimum possible sum of Bitwise XOR of all the pairs from the array ; Stores the XOR of all pairs ( i , j ) ; Store the XOR of all pairs ( i , j ) ; Update Bitwise XOR ; Sort the vector ; Initialize variables to store maximum and minimum possible sums ; Find the minimum sum possible ; Reverse the vector , v ; Find the maximum sum possible ; Print the result ; Driver code
import java . util . * ; class pair { int first , second , third ; pair ( int first , int second , int third ) { this . first = first ; this . second = second ; this . third = third ; } } class GFG { static int findSum ( ArrayList < pair > v , int n ) { Map < Integer , Boolean > um = new HashMap < > ( ) ; int res = 0 ; int cnt = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( cnt == n ) break ; int x = v . get ( i ) . second ; int y = v . get ( i ) . third ; int xorResult = v . get ( i ) . first ; if ( um . get ( x ) == null && um . get ( y ) == null ) { res += xorResult ; um . put ( x , true ) ; um . put ( y , true ) ; cnt += 2 ; } } return res ; } static void findMaxMinSum ( int a [ ] , int n ) { ArrayList < pair > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int xorResult = a [ i ] ^ a [ j ] ; v . add ( new pair ( xorResult , a [ i ] , a [ j ] ) ) ; } } Collections . sort ( v , ( aa , b ) -> aa . first - b . first ) ; int maxi = 0 , mini = 0 ; mini = findSum ( v , n ) ; Collections . reverse ( v ) ; maxi = findSum ( v , n ) ; System . out . print ( mini + " ▁ " + maxi ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; findMaxMinSum ( arr , N ) ; } }