We are given an array $A$, an integer $Z$ and a value $Q$. The goal is to maximize the sum of $A$, by performing following operation any number of times: We can select exactly $Z$ elements from the given array and perform XOR on each of them with $Q$.
Is there any data structure I can use which can perform this efficiently or any algorithm I am not aware of?
I tried finding each element's maximum possible value (using XOR/ignoring it), sorting the array and then making the selection but it did not work, which leads me to believe that the greedy approach won't work here.
I am primarily looking for an algorithm that can help or a data structure, not necessarily the code.
For example, given the array $[1, 2, 3, 4, 5], Z = 2$ and $Q = 4$, the answer is 23 as I can take XOR of 1 and 2 with 4 and of 3 and 4 with 4 as well.
Edit: The sum 23 is obtained as follows: We need to select Z (2) values at a time. So we select 1 and 2 and obtain their XOR with Q(4), which makes it 5 and 6. We then select 3 and 4 and obtain their XOR with Q, which makes them 7 and 0. Thus the final array becomes $[5,6,7,0,5] which is equal to 23 and is maximum possible sum.