1829. Maximum XOR for Each Query
Difficulty: Medium
Topics: Array, Bit Manipulation, Prefix Sum
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:
Return an array answer, where answer[i] is the answer to the ith query.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We need to efficiently calculate the XOR of elements in the array and maximize the result using a value k such that k is less than 2^maximumBit. Here's the approach for solving this problem:
Maximizing XOR:
The maximum number we can XOR with any prefix sum for maximumBit bits is ( 2^{text{maximumBit}} - 1 ). This is because XORing with a number of all 1s (i.e., 111...1 in binary) will always maximize the result.
Prefix XOR Calculation:
Instead of recalculating the XOR for each query, we can maintain a cumulative XOR for the entire array. Since XOR has the property that A XOR B XOR B = A, removing the last element from the array can be achieved by XORing out that element from the cumulative XOR.
Algorithm:
Let's implement this solution in PHP: 1829. Maximum XOR for Each Query
Explanation:
Calculate maxNum:
- maxNum is calculated as 2^maximumBit - 1, which is the number with all 1s in binary for the specified bit length.
Initial XOR Calculation:
- We XOR all elements in nums to get the cumulative XOR (currentXOR), representing the XOR of all numbers in the array.
Iterate Backwards:
- We start from the last element in nums and calculate the maximum XOR for each step:
- currentXOR ^ maxNum gives the maximum k for the current state.
- Append k to answer.
- We then XOR the last element of nums with currentXOR to "remove" it from the XOR sum for the next iteration.
Return the Answer:
- Since we processed the list in reverse, answer will contain the values in reverse order, so the final list is already arranged correctly for our requirements.
Complexity Analysis
This code is efficient and should handle the upper limits of the constraints well.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Maximum XOR for Each Query. For more information, please follow other related articles on the PHP Chinese website!