1911. Maximum Alternating Subsequence Sum
SourceBiweekly Contest 55 Q3DifficultyMediumRating1785
Description
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 <= 1051 <= nums[i] <= 105
Solutions
Solution 1: Dynamic Programming
Thinking
Enumerating subsequences is exponential. With \(n\le 10^5\) we need a linear DP on the parity of the last chosen index.
Let \(f[i]\) be the best alternating sum of the first \(i\) elements whose last pick sits on an odd slot (subtracted), and \(g[i]\) the best whose last pick sits on an even slot (added). Element \(x\) is either appended to the opposite parity or skipped.
The recurrences are \(f[i]=\max(g[i-1]-x,f[i-1])\) and \(g[i]=\max(f[i-1]+x,g[i-1])\); the answer is the larger of \(f[n]\) and \(g[n]\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 | |
Solution 2: Dynamic Programming (Space Optimization)
Thinking
Only the previous \(f\) and \(g\) are read, so two scalars updated left to right replace the arrays and drop extra space to \(O(1)\).
\(f[i]\) and \(g[i]\) depend only on the previous index, so two variables are enough and the space complexity is \(O(1)\).
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |