Maximum Absolute Sum of Any Subarray - 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 + ... + numsr-1 + numsr).

Return the maximum absolute sum of any (possibly empty) subarray of nums.

Note: abs(x) is defined as follows:

  • If x is a negative integer, then abs(x) = -x.
  • If x is a non-negative integer, then abs(x) = x.

Input & Output

Example 1 — Mixed Positive and Negative
$ Input: nums = [1,-3,2,1,-4]
Output: 5
💡 Note: The subarray [1,-3,2,1] has sum = 1, absolute sum = |1| = 1. The subarray [2,1] has sum = 3, absolute sum = |3| = 3. The subarray [-4] has sum = -4, absolute sum = |-4| = 4. The maximum absolute sum is 4.
Example 2 — All Positive Numbers
$ Input: nums = [2,-5,1,-4,3,-1]
Output: 8
💡 Note: The subarray [-5,1,-4] has sum = -8, absolute sum = |-8| = 8. This gives the maximum absolute sum.
Example 3 — Single Element
$ Input: nums = [-3]
Output: 3
💡 Note: The only subarray is [-3] with sum = -3, absolute sum = |-3| = 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Absolute Sum of Any SubarrayInput: [1, -3, 2, 1, -4]1-321-4Max Positive Sum: [2,1] = 3Min Sum: [-4] = -4max(3, |-4|) = max(3, 4) = 4Output: 4
Understanding the Visualization
1
Input Array
Given array with mixed positive and negative numbers
2
Find Extremes
Find maximum positive sum and minimum negative sum
3
Maximum Absolute
Return the larger absolute value
Key Takeaway
🎯 Key Insight: The maximum absolute sum is the larger of the maximum positive subarray sum and absolute value of minimum negative subarray sum
Asked in
Amazon 15 Microsoft 12
28.0K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen