Maximum Sum of Alternating Subsequence With Distance at Least K Problem
Description
LeetCode Problem 3915.
You are given an integer array nums of length n and an integer k.
Pick a subsequence with indices 0 <= i_1 < i_2 < ... < i_m < n such that:
- For every
1 <= t < m,i_(t+1) - i_t >= k. - The selected values form a strictly alternating sequence. In other words, either:
nums[i_1] < nums[i_2] > nums[i_3] < ..., ornums[i_1] > nums[i_2] < nums[i_3] > ...
A subsequence of length 1 is also considered strictly alternating. The score of a valid subsequence is the sum of its selected values.
Return an integer denoting the maximum possible score of a valid subsequence.
Example 1:
Input: nums = [5,4,2], k = 2
Output: 7
Explanation:
An optimal choice is indices [0, 2], which gives values [5, 2].
- The distance condition holds because 2 - 0 = 2 >= k.
- The values are strictly alternating because 5 > 2.
The score is 5 + 2 = 7.
Example 2:
Input: nums = [3,5,4,2,4], k = 1
Output: 14
Explanation:
An optimal choice is indices [0, 1, 3, 4], which gives values [3, 5, 2, 4].
- The distance condition holds because each pair of consecutive chosen indices differs by at least k = 1.
- The values are strictly alternating since 3 < 5 > 2 < 4.
The score is 3 + 5 + 2 + 4 = 14.
Example 3:
Input: nums = [5], k = 1
Output: 5
Explanation:
The only valid subsequence is [5]. A subsequence with 1 element is always strictly alternating, so the score is 5.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^51 <= k <= n
Solution
Approach: Dynamic Programming + Binary Indexed Tree
State. Let f[i][0] be the best sum of a valid subsequence that ends at index i with a valley (the next chosen element must be larger), and f[i][1] the best sum when it ends with a peak (the next element must be smaller).
Transitions. The previous chosen index j must satisfy j <= i - k:
f[i][0] = nums[i] + max(0, max f[j][1])over thosejwithnums[j] > nums[i].f[i][1] = nums[i] + max(0, max f[j][0])over thosejwithnums[j] < nums[i].
The answer is the maximum of all f[i][0] and f[i][1]. Starting a subsequence at i corresponds to the 0 inside the maximum.
Speeding it up. Each transition is a prefix or suffix maximum over values, with entries added over time. Compress the values to ranks 1..m and keep two Binary Indexed Trees that support "update with max" and "prefix max". The first tree is indexed by rank and holds f[.][0], which answers "all smaller values". The second is indexed by the reversed rank m + 1 - rank and holds f[.][1], which answers "all larger values".
To respect the distance rule, insert the states of index i - k into the trees just before computing index i, so only indices up to i - k are visible.
Complexity: time O(n log m) and space O(n + m), where n is the array length and m the number of distinct values.
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, val: int) -> None:
while x <= self.n:
self.c[x] = max(self.c[x], val)
x += x & -x
def query(self, x: int) -> int:
ans = 0
while x > 0:
ans = max(ans, self.c[x])
x -= x & -x
return ans
class Solution:
def maxAlternatingSum(self, nums: List[int], k: int) -> int:
vals = sorted(set(nums))
m = len(vals)
rank = {v: i + 1 for i, v in enumerate(vals)}
bit0 = BinaryIndexedTree(m)
bit1 = BinaryIndexedTree(m)
n = len(nums)
f = [[0, 0] for _ in range(n)]
ans = 0
for i, x in enumerate(nums):
if i >= k:
r = rank[nums[i - k]]
bit0.update(r, f[i - k][0])
bit1.update(m + 1 - r, f[i - k][1])
r = rank[x]
f[i][0] = x + bit1.query(m - r)
f[i][1] = x + bit0.query(r - 1)
ans = max(ans, f[i][0], f[i][1])
return ans