Find the Maximum Sequence Value of Array - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,6,7], k = 1
Output: 5
💡 Note: Choose subsequence [2,7]. First half: OR(2) = 2. Second half: OR(7) = 7. XOR: 2 ^ 7 = 5
Example 2 — Larger k
$ Input: nums = [4,2,5,6,7], k = 2
Output: 2
💡 Note: Choose subsequence [4,5,6,7]. First half: OR(4,5) = 5. Second half: OR(6,7) = 7. XOR: 5 ^ 7 = 2
Example 3 — All Same Values
$ Input: nums = [3,3,3,3], k = 2
Output: 0
💡 Note: Any subsequence gives OR(3,3) = 3 for both halves. XOR: 3 ^ 3 = 0

Constraints

  • 1 ≤ k ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 26
  • nums.length is even
  • 2 * k ≤ nums.length

Visualization

Tap to expand
Maximum Sequence Value of Array INPUT nums array: 2 i=0 6 i=1 7 i=2 Binary: 010 110 111 k = 1 Subseq size: 2*k = 2 Find max value: (OR of first k) XOR (OR of last k) ALGORITHM STEPS 1 Precompute Left ORs DP: all OR values using k elements from left 2 Precompute Right ORs DP: all OR values using k elements from right 3 XOR Combinations For each split point, XOR left and right ORs 4 Track Maximum Keep best XOR result with early pruning Example: seq=[2,7] Left OR: 2 = 010 Right OR: 7 = 111 XOR: 010^111 = 101 = 5 FINAL RESULT All Valid Subsequences: Seq L XOR R [2,6] 2^6 = 4 [2,7] 2^7 = 5 [6,7] 6^7 = 1 [6,2] 6^2 = 4 Maximum Value 5 Output: 5 [OK] Verified Key Insight: Use DP to precompute all possible OR values achievable with exactly k elements from prefix and suffix. Since OR values are bounded (max 128 possible values for small nums), we can efficiently enumerate all combinations. Early pruning skips states that cannot improve the current maximum XOR value. TutorialsPoint - Find the Maximum Sequence Value of Array | Optimized DP with Early Pruning
Asked in
Google 15 Facebook 12 Microsoft 8
12.0K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen