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:
Below is the implementation of the above approach:
// 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));
}
}
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.
#arrays #bit magic #combinatorial #dynamic programming #bitwise-xor #subsequence #subset