MediumNo. 2036LeetCode Premium

Maximum Alternating Subarray Sum — LeetCode 2036 Python Solution

Topics
Array, Dynamic Programming
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

PythonSolution
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

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard

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.

Free to download. Check it runs on your machine, then pick a plan.