Maximum sum of Bitwise XOR of all elements of two equal length subsets

Given an array arr[] of N integers, where N is an even number. The task is to divide the given N integers into two equals subset such that the sum of Bitwise XOR of all elements of two subsets is maximum.

Examples:

Input: N= 4, arr[] = {1, 2, 3, 4} 
Output: 10 
Explanation:
There are 3 ways possible: 
(1, 2)(3, 4) = (1^2)+(3^4) = 10
(1, 3)(2, 4) = (1^3)+(2^3) = 8
(1, 4)(2, 3) = (1^4)+(2^3) = 6
Hence, the maximum sum = 10

Input: N= 6, arr[] = {4, 5, 3, 2, 5, 6} 
Output: 17

 

Naive Approach: The idea is to check every possible distribution of N/2 pairs. Print the Bitwise XOR of the sum of all elements of two subsets which is maximum.



Time Complexity: O(N*N!)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming Using Bit Masking. Follow the below steps to solve the problem:

  1. Initially, the bitmask is 0, if the bit is set then the pair is already picked.
  2. Iterate through all the possible pairs and check if it is possible to pick a pair i.e., the bits of i and j are not set in the mask:
    • If it is possible to take the pair then find the Bitwise XOR sum for the current pair and check for the next pair recursively.
    • Else check for the next pair of elements.
  3. Keep updating the maximum XOR pair sum in the above step for each recursive call.
  4. Print the maximum value of all possible pairs stored in dp[mask].

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function that finds the maximum
// Bitwise XOR sum of the two subset
int xorSum(int a[], int n,
           int mask, int dp[])
{
  // Check if the current state is
  // already computed
  if (dp[mask] != -1)
  {
    return dp[mask];
  }
 
  // Initialize answer to minimum value
  int max_value = 0;
 
  // Iterate through all possible pairs
  for (int i = 0; i < n; i++)
  {
    for (int j = i + 1; j < n; j++)
    {
 
      // Check whether ith bit and
      // jth bit of mask is not
      // set then pick the pair
      if (i != j &&
         (mask & (1 << i)) == 0 &&
         (mask & (1 << j)) == 0)
      {
 
        // For all possible pairs
        // find maximum value pick
        // current a[i], a[j] and
        // set i, j th bits in mask
        max_value = max(max_value, (a[i] ^ a[j]) +
                        xorSum(a, n, (mask | (1 << i) |
                                               (1 << j)), dp));
      }
    }
  }
 
  // Store the maximum value
  // and return the answer
  return dp[mask] = max_value;
}
 
// Driver Code
int main()
{
   int n = 4;
 
   // Given array arr[]
   int arr[] = { 1, 2, 3, 4 };
 
   // Declare Initialize the dp states
   int dp[(1 << n) + 5];
   memset(dp, -1, sizeof(dp));
 
   // Function Call
   cout << (xorSum(arr, n, 0, dp));
}
 
// This code is contributed by Rohit_ranjan
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
import java.io.*;
 
public class GFG {
 
    // Function that finds the maximum
    // Bitwise XOR sum of the two subset
    public static int xorSum(int a[], int n,
                             int mask, int[] dp)
    {
        // Check if the current state is
        // already computed
        if (dp[mask] != -1) {
            return dp[mask];
        }
 
        // Initialize answer to minimum value
        int max_value = 0;
 
        // Iterate through all possible pairs
        for (int i = 0; i < n; i++) {
 
            for (int j = i + 1; j < n; j++) {
 
                // Check whether ith bit and
                // jth bit of mask is not
                // set then pick the pair
                if (i != j
                    && (mask & (1 << i)) == 0
                    && (mask & (1 << j)) == 0) {
 
                    // For all possible pairs
                    // find maximum value pick
                    // current a[i], a[j] and
                    // set i, j th bits in mask
                    max_value = Math.max(
                        max_value,
                        (a[i] ^ a[j])
                            + xorSum(a, n,
                                     (mask | (1 << i)
                                      | (1 << j)),
                                     dp));
                }
            }
        }
 
        // Store the maximum value
        // and return the answer
        return dp[mask] = max_value;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int n = 4;
 
        // Given array arr[]
        int arr[] = { 1, 2, 3, 4 };
 
        // Declare Initialize the dp states
        int dp[] = new int[(1 << n) + 5];
        Arrays.fill(dp, -1);
 
        // Function Call
        System.out.println(xorSum(arr, n, 0, dp));
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function that finds the maximum
# Bitwise XOR sum of the two subset
def xorSum(a, n, mask, dp):
 
    # Check if the current state is
    # already computed
    if(dp[mask] != -1):
        return dp[mask]
 
    # Initialize answer to minimum value
    max_value = 0
 
    # Iterate through all possible pairs
    for i in range(n):
        for j in range(i + 1, n):
 
            # Check whether ith bit and
            # jth bit of mask is not
            # set then pick the pair
            if(i != j and
              (mask & (1 << i)) == 0 and
              (mask & (1 << j)) == 0):
 
                # For all possible pairs
                # find maximum value pick
                # current a[i], a[j] and
                # set i, j th bits in mask
                max_value = max(max_value,
                               (a[i] ^ a[j]) +
                                xorSum(a, n,
                                (mask | (1 << i) |
                                (1 << j)), dp))
 
    # Store the maximum value
    # and return the answer
    dp[mask] = max_value
 
    return dp[mask]
 
# Driver Code
n = 4
 
# Given array arr[]
arr = [ 1, 2, 3, 4 ]
 
# Declare Initialize the dp states
dp = [-1] * ((1 << n) + 5)
 
# Function call
print(xorSum(arr, n, 0, dp))
 
# This code is contributed by Shivam Singh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
 
// Function that finds the maximum
// Bitwise XOR sum of the two subset
public static int xorSum(int []a, int n,
                         int mask, int[] dp)
{
     
    // Check if the current state is
    // already computed
    if (dp[mask] != -1)
    {
        return dp[mask];
    }
 
    // Initialize answer to minimum value
    int max_value = 0;
 
    // Iterate through all possible pairs
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // Check whether ith bit and
            // jth bit of mask is not
            // set then pick the pair
            if (i != j &&
               (mask & (1 << i)) == 0 &&
               (mask & (1 << j)) == 0)
            {
 
                // For all possible pairs
                // find maximum value pick
                // current a[i], a[j] and
                // set i, j th bits in mask
                max_value = Math.Max(
                            max_value,
                            (a[i] ^ a[j]) +
                            xorSum(a, n, (mask |
                            (1 << i) | (1 << j)), dp));
            }
        }
    }
 
    // Store the maximum value
    // and return the answer
    return dp[mask] = max_value;
}
 
// Driver Code
public static void Main(String []args)
{
    int n = 4;
 
    // Given array []arr
    int []arr = { 1, 2, 3, 4 };
 
    // Declare Initialize the dp states
    int []dp = new int[(1 << n) + 5];
    for(int i = 0; i < dp.Length; i++)
        dp[i] = -1;
 
    // Function call
    Console.WriteLine(xorSum(arr, n, 0, dp));
}
}
 
// This code is contributed by amal kumar choubey
chevron_right

Output: 
10


 

Time Complexity: O(N2*2N), where N is the size of the given array
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :