MediumNo. 1749
Maximum Absolute Sum of Any Subarray — LeetCode 1749 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0045 | Jump Game II | Medium |
| 0053 | Maximum Subarray | Medium |
| 0055 | Jump Game | Medium |
| 0063 | Unique Paths II | Medium |
| 0064 | Minimum Path Sum | Medium |
| 0085 | Maximal Rectangle | Hard |
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.