[LeetCode] Maximum XOR of Subsequences

3681. Maximum XOR of Subsequences

You are given an integer array nums of length n where each element is a non-negative integer.

Select two subsequences of nums (they may be empty and are allowed to overlap), each preserving the original order of elements, and let:

  • X be the bitwise XOR of all elements in the first subsequence.
  • Y be the bitwise XOR of all elements in the second subsequence.

Return the maximum possible value of X XOR Y.

Note: The XOR of an empty subsequence is 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
bool BIT(int x, int i) {
return (x>>i) & 1;
}
public:
int maxXorSubsequences(vector<int>& nums) {
vector<long long> basis(32);
auto insert = [&](long long x) {
for(int i = 31; i >= 0; i--) {
if(!BIT(x,i)) continue;
if(!basis[i]) {
basis[i] = x;
return;
}
x ^= basis[i];
}
return;
};
for(auto& n : nums) insert(n);
int res = 0;
for(int i = 31; i >= 0; i--) {
if(!BIT(res,i)) res ^= basis[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/09/19/PS/LeetCode/maximum-xor-of-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.