Tier: Hard (Q3) | Marks: 50 | Topic: Bit Manipulation / Gaussian Elimination
Given an array of
Sample Input:
arr = [3, 5, 6, 8, 10, 12] (N=6, choose 3)
Sample Output:
15
Constraints:
Build a linear XOR basis (Gaussian Elimination over GF(2)) from the array. The maximum XOR of any subset (regardless of size) is obtained by greedily activating basis vectors from highest bit to lowest. For the size constraint (
$N/2$ elements), the key insight is: if we can achieve max XOR from any subset, the$N/2$ size constraint can usually be satisfied by adding "neutral" XOR pairs (elements that XOR to 0) to balance parity — but this depends on whether the basis spans a space including size-parity.
For small
For
For
from itertools import combinations
def max_xor_half_subset(arr):
n = len(arr)
half = n // 2
best = 0
for subset in combinations(arr, half):
xor_val = 0
for x in subset: xor_val ^= x
best = max(best, xor_val)
return best
arr = list(map(int, input().split()))
print(max_xor_half_subset(arr))#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL);
int n; cin >> n;
vector<int> arr(n);
for (int& x : arr) cin >> x;
int half = n / 2;
long long best = 0;
// Enumerate all subsets of size n/2
for (int mask = 0; mask < (1 << n); mask++) {
if (__builtin_popcount(mask) != half) continue;
long long xorv = 0;
for (int i = 0; i < n; i++)
if (mask >> i & 1) xorv ^= arr[i];
best = max(best, xorv);
}
cout << best << "\n";
return 0;
}XOR properties used here:
a ^ a = 0(self-cancellation)a ^ 0 = a(identity)- XOR is commutative and associative
Know MSB: msb(x) = x.bit_length() - 1 in Python, 31 - __builtin_clz(x) in C++.