Maximum Alternating Subsequence Sum — LeetCode 1911 Python Solution
- Problem
- #1911
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
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])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1911. Maximum Alternating Subsequence Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1911. Maximum Alternating Subsequence Sum?
- LeetCode 1911. Maximum Alternating Subsequence Sum is rated Medium on LeetCode.
- What topics does LeetCode 1911. Maximum Alternating Subsequence Sum cover?
- LeetCode 1911. Maximum Alternating Subsequence Sum is tagged Array and Dynamic Programming on LeetCode.