3845. Maximum Subarray XOR with Bounded Range
Description
You are given a non-negative integer array nums and an integer k.
You must select a subarray of nums such that the difference between its maximum and minimum elements is at most k. The value of this subarray is the bitwise XOR of all elements in the subarray.
Return an integer denoting the maximum possible value of the selected subarray.
Example 1:
Input: nums = [5,4,5,6], k = 2
Output: 7
Explanation:
- Select the subarray
[5, 4, 5, 6]. - The difference between its maximum and minimum elements is
6 - 4 = 2 <= k. - The value is
4 XOR 5 XOR 6 = 7.
Example 2:
Input: nums = [5,4,5,6], k = 1
Output: 6
Explanation:
- Select the subarray
[5, 4, 5, 6]. - The difference between its maximum and minimum elements is
6 - 6 = 0 <= k. - The value is 6.
Constraints:
1 <= nums.length <= 4 * 1040 <= nums[i] < 2150 <= k < 215
Solutions
Solution 1
Thinking
A subarray must satisfy \(\max-\min \le k\) while maximizing its XOR. \(n \le 4 \times 10^4\) and values lie below \(2^{15}\).
A subarray XOR is the XOR of two prefix XORs. For a fixed right end the legal left ends form a \(\max-\min\) window, inside which we query the best prefix XOR.
Monotonic deques shrink the window; a binary trie inserts and deletes prefix XORs and greedily takes the opposite bit.
As the right end advances, the window and the trie slide together; each prefix enters and leaves once.
1 | |
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
1 | |
1 | |