Maximum Absolute Sum of Any Subarray — LeetCode 1749 Python Solution
- Problem
- #1749
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.