We want to select 2*k elements and split them into two groups of size k each, maximizing the value (OR of first group) XOR (OR of second group). Since k is small (up to 8), we can use bitmask DP to try all possible ways to split the selected elements.
// Omitted due to combinatorial explosion for large n, feasible for small k only
1
// Omitted due to combinatorial explosion for large n, feasible for small k only
1
// Omitted due to combinatorial explosion for large n, feasible for small k only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from itertools import combinations
classSolution:
defmaxSequenceValue(self, nums: list[int], k: int) -> int:
from itertools import combinations
n = len(nums)
ans =0for pick in combinations(range(n), 2*k):
idxs = list(pick)
for mask in range(1<<(2*k)):
if bin(mask).count('1') != k:
continue a = b =0for i in range(2*k):
if (mask>>i)&1:
a |= nums[idxs[i]]
else:
b |= nums[idxs[i]]
ans = max(ans, a^b)
return ans
1
// Omitted due to combinatorial explosion for large n, feasible for small k only
1
// Omitted due to combinatorial explosion for large n, feasible for small k only