MediumNo. 1749

Maximum Absolute Sum of Any Subarray — LeetCode 1749 Python Solution

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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

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 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.

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