Maximum and minimum sum of Bitwise XOR of pairs from an array | C # program for the 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
using System ; using System . Collections . Generic ; class pair : IComparable < pair > { public int first , second , third ; public pair ( int first , int second , int third ) { this . first = first ; this . second = second ; this . third = third ; } public int CompareTo ( pair p ) { return this . second - p . first ; } } class GFG { static int findSum ( List < pair > v , int n ) { Dictionary < int , Boolean > um = new Dictionary < int , Boolean > ( ) ; int res = 0 ; int cnt = 0 ; for ( int i = 0 ; i < v . Count ; i ++ ) { if ( cnt == n ) break ; int x = v [ i ] . second ; int y = v [ i ] . third ; int xorResult = v [ i ] . first ; if ( ! um . ContainsKey ( x ) && ! um . ContainsKey ( y ) ) { res += xorResult ; um . Add ( x , true ) ; um . Add ( y , true ) ; cnt += 2 ; } } return res ; } static void findMaxMinSum ( int [ ] a , int n ) { List < pair > v = new List < pair > ( ) ; 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 ] ) ) ; } } v . Sort ( ) ; int maxi = 0 , mini = 0 ; mini = findSum ( v , n ) ; v . Reverse ( ) ; maxi = findSum ( v , n ) ; Console . Write ( mini + " ▁ " + maxi ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int N = arr . Length ; findMaxMinSum ( arr , N ) ; } }