Maximum Alternating Subsequence Sum Problem
Description
LeetCode Problem 1911.
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
- For example, the alternating sum of
[4,2,5,3]is(4 + 5) - (2 + 3) = 4.
Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Example 1:
Input: nums = [4,2,5,3]
Output: 7
Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
Example 2:
Input: nums = [5,6,7,8]
Output: 8
Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
Example 3:
Input: nums = [6,2,1,2,4,5]
Output: 10
Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Dynamic Programming
Track two values after looking at the first i numbers:
f[i]: the best alternating sum of a subsequence that currently has an even length (the next element it takes would be added).g[i]: the best alternating sum of a subsequence that currently has an odd length (the next element it takes would be subtracted).
For the i-th number x, we either skip it or take it:
f[i] = max(f[i-1], g[i-1] - x): skip, or extend an odd-length subsequence by subtractingx.g[i] = max(g[i-1], f[i-1] + x): skip, or extend an even-length subsequence by addingx.
Start with f[0] = g[0] = 0 (the empty subsequence). The answer is max(f[n], g[n]). Since each step needs only the previous row, the arrays can be replaced by two variables.
Complexity: O(n) time and O(n) space (O(1) with two variables).
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
f = [0] * (n + 1)
g = [0] * (n + 1)
for i, x in enumerate(nums, 1):
f[i] = max(g[i - 1] - x, f[i - 1])
g[i] = max(f[i - 1] + x, g[i - 1])
return max(f[n], g[n])