題目連結 | 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
]