Find the Maximum Sequence Value of Array Problem
#3287
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3287.
You are given an integer array nums and a positive integer k.
The value of a sequence seq of size 2 * x is defined as:
(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1]).
Return the maximum value of any subsequence of nums having size 2 * k.
Example 1:
Input: nums = [2,6,7], k = 1
Output: 5
Explanation:
The subsequence [2, 7] has the maximum value of 2 XOR 7 = 5.
Example 2:
Input: nums = [4,2,5,6,7], k = 2
Output: 2
Explanation:
The subsequence [4, 5, 6, 7] has the maximum value of (4 OR 5) XOR (6 OR 7) = 2.
Constraints:
2 <= nums.length <= 4001 <= nums[i] < 2^71 <= k <= nums.length / 2
Solution
Approach: Prefix and Suffix Reachable ORs
A sequence of length 2k is split into a first half and a second half, each of k elements taken in order, and its value is (OR of the first half) XOR (OR of the second half). Since every nums[i] < 128, there are only 128 possible OR values.
f[i][j][x]is true if somejelements of the prefixnums[0..i-1]have OR equal tox.g[i][j][y]is true if somejelements of the suffixnums[i..n-1]have OR equal toy.
Both tables are filled by choosing to skip or take each element. Then for every split point i from k to n - k, combine every x with f[i][k][x] and every y with g[i][k][y], and keep the largest x ^ y.
Complexity:
- Time complexity:
O(n * k * 2^7 + n * 2^14) - Space complexity:
O(n * k * 2^7)
class Solution:
def maxValue(self, nums: List[int], k: int) -> int:
m = 1 << 7
n = len(nums)
f = [[[False] * m for _ in range(k + 2)] for _ in range(n + 1)]
f[0][0][0] = True
for i in range(n):
for j in range(k + 1):
for x in range(m):
f[i + 1][j][x] |= f[i][j][x]
f[i + 1][j + 1][x | nums[i]] |= f[i][j][x]
g = [[[False] * m for _ in range(k + 2)] for _ in range(n + 1)]
g[n][0][0] = True
for i in range(n, 0, -1):
for j in range(k + 1):
for y in range(m):
g[i - 1][j][y] |= g[i][j][y]
g[i - 1][j + 1][y | nums[i - 1]] |= g[i][j][y]
ans = 0
for i in range(k, n - k + 1):
for x in range(m):
if f[i][k][x]:
for y in range(m):
if g[i][k][y]:
ans = max(ans, x ^ y)
return ans