题目链接 | 3277. 查询子数组最大异或值 |
---|---|
思路 | 区间DP(区间异或值计算)+ 区间DP(区间最大值查询) |
题解链接 | 区间 DP 套区间 DP(Python/Java/C++/Go) |
关键点 | 1.区间异或值计算:\(\text{xor}_{i,j}=\text{xor}_{i,j-1}\oplus\text{xor}_{i+1,j}\quad\quad\) 2. 区间最大值:\(\text{maxv}_{i,j}=\max(\text{xor}_{i,j}, \text{maxv}_{i+1,j}, \text{maxv}_{i,j-1})\) |
时间复杂度 | \(O(n^2+q)\) |
空间复杂度 | \(O(n^2)\) |
代码实现:
class Solution:def maximumSubarrayXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:n = len(nums)xor = [[0] * n for _ in range(n)]maxv = [[0] * n for _ in range(n)]for i in range(n-1, -1, -1):maxv[i][i] = xor[i][i] = nums[i]for j in range(i+1, n):xor[i][j] = xor[i][j-1] ^ xor[i+1][j]maxv[i][j] = max(xor[i][j], maxv[i+1][j], maxv[i][j-1])return [maxv[l][r] for l, r in queries]