Maximum Alternating Subsequence Sum — LeetCode 1911 Python Solution

MediumArrayDynamic Programming
Problem
#1911
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview