1. 解题思路
这一题其实是一个比较典型的动态规划的题目,可惜我没有自力搞定,是看大佬的算法才想明白的,着实有点惭愧……
我们首先按照题目计算出任意子序列 s i , j s_{i,j} si,j的XOR score,根据题中迭代计算规则,不难得到递推关系:
s i , j = s i , j − 1 ⊕ s i + 1 , j s_{i, j} = s_{i, j-1} \oplus s_{i+1, j} si,j=si,j−1⊕si+1,j
然后,我们要求任意范围 s i , j s_{i, j} si,j内的最大XOR score,同样有递推关系:
S i , j = max ( s i , j , S i , j − 1 , S i + 1 , j ) S_{i, j} = \max(s_{i, j}, S_{i, j-1}, S_{i+1, j}) Si,j=max(si,j,Si,j−1,Si+1,j)
由此,我们即可得到任意范围内的max XOR score的答案了。此时,我们根据具体的query找到对应的答案即可。
2. 代码实现
给出python代码实现如下:
class Solution:
def maximumSubarrayXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:
n = len(nums)
score = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
score[i][i] = nums[i]
for d in range(1, n):
for l in range(n - d):
r = l + d
score[l][r] = score[l][r-1] ^ score[l+1][r]
answer = deepcopy(score)
for d in range(1, n):
for l in range(n - d):
r = l + d
answer[l][r] = max(score[l][r], answer[l+1][r], answer[l][r-1])
ans = [answer[l][r] for l, r in queries]
return ans
提交代码评测得到:耗时8065ms,占用内存163.1MB。