Maximum Absolute Sum of Any Subarray — LeetCode 1749 Python Solution

MediumArrayDynamic Programming
Problem
#1749
Reading time
2 min

The problem

You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ...

Example

Input
nums = [1,-3,2,3,-4]
Output
5
Explanation
The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.

Python solution

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

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 1749. Maximum Absolute Sum of Any Subarray 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 1749. Maximum Absolute Sum of Any Subarray?
LeetCode 1749. Maximum Absolute Sum of Any Subarray is rated Medium on LeetCode.
What topics does LeetCode 1749. Maximum Absolute Sum of Any Subarray cover?
LeetCode 1749. Maximum Absolute Sum of Any Subarray 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