[LeetCode] Maximum XOR for Each Query

1829. Maximum XOR for Each Query

You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:

  1. Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR … XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.
  2. Remove the last element from the current array nums.

Return an array answer, where answer[i] is the answer to the ith query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int helper(int k, int ma) {
int res = 0;
for(int i = 0; i < ma; i++) {
if(k & (1<<i)) continue;
res ^= (1<<i);
}
return res;
}
public:
vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {
int pxor = 0;
for(auto& n : nums) pxor ^= n;
vector<int> res;
for(int i = nums.size() - 1; i >= 0; i--) {
res.push_back(helper(pxor, maximumBit));
pxor ^= nums[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/21/PS/LeetCode/maximum-xor-for-each-query/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.