Maximum Alternating Subarray Sum — LeetCode 2036 Python Solution

MediumLeetCode PremiumArrayDynamic Programming
Problem
#2036
Reading time
2 min

The problem

A subarray of a 0-indexed integer array is a contiguous non-empty sequence of elements within an array. The alternating subarray sum of a subarray that ranges from index i to j (inclusive, 0 <= i <= j < nums.length) is nums[i] - nums[i+1] + nums[i+2] - ...

Example

Input
nums = [3,-1,1,2]
Output
5
Explanation
The subarray [3,-1,1] has the largest alternating subarray sum.

Python solution

Python
class Solution:
    def maximumAlternatingSubarraySum(self, nums: List[int]) -> int:
        ans = f = g = -inf
        for x in nums:
            f, g = max(g, 0) + x, f - x
            ans = max(ans, f, g)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2036. Maximum Alternating Subarray 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 2036. Maximum Alternating Subarray Sum?
LeetCode 2036. Maximum Alternating Subarray Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 2036. Maximum Alternating Subarray Sum?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2036. Maximum Alternating Subarray Sum?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2036. Maximum Alternating Subarray Sum cover?
LeetCode 2036. Maximum Alternating Subarray Sum is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 2036. Maximum Alternating Subarray Sum a premium problem?
Yes. LeetCode 2036. Maximum Alternating Subarray Sum is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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