[LeetCode] Maximum XOR Score Subarray Queries

3277. Maximum XOR Score Subarray Queries

You are given an array nums of n integers, and a 2D integer array queries of size q, where queries[i] = [li, ri].

For each query, you must find the maximum XOR score of any subarray of nums[li..ri].

The XOR score of an array a is found by repeatedly applying the following operations on a so that only one element remains, that is the score:

  • Simultaneously replace a[i] with a[i] XOR a[i + 1] for all indices i except the last one.
  • Remove the last element of a.

Return an array answer of size q where answer[i] is the answer to query i.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int dp[2020][2020], dpp[2020][2020];
class Solution {
int helper(vector<int>& A, int l, int r) {
if(dp[l][r] != -1) return dp[l][r];
if(l == r) return dp[l][r] = dpp[l][r] = A[l];
int& res = dp[l][r] = max({helper(A,l+1,r), helper(A,l,r-1)});
dpp[l][r] = dpp[l+1][r] ^ dpp[l][r-1];
res = max(res, dpp[l][r]);
return res;
}
public:
vector<int> maximumSubarrayXor(vector<int>& nums, vector<vector<int>>& queries) {
memset(dp,-1,sizeof dp);
memset(dpp,-1,sizeof dpp);
vector<int> res;
for(auto& q : queries) {
res.push_back(helper(nums,q[0],q[1]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/01/PS/LeetCode/maximum-xor-score-subarray-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.