Maximum Absolute Sum of Any Subarray - Problem

Given an integer array nums, you need to find the maximum absolute sum of any subarray within it.

The absolute sum of a subarray is the absolute value of the sum of all elements in that subarray. For example, if a subarray sums to -15, its absolute sum is 15. If it sums to 8, its absolute sum is 8.

Your task: Return the maximum possible absolute sum among all possible subarrays (including empty subarrays with sum 0).

Key insight: The maximum absolute sum will be either the maximum positive sum or the absolute value of the minimum negative sum of any subarray.

Input & Output

example_1.py — Basic Case
$ Input: [1, -3, 2, 3, -4]
› Output: 5
šŸ’” Note: The subarray [2, 3] has sum 5, which has the maximum absolute value among all subarrays.
example_2.py — All Negative
$ Input: [-2, -3, -1]
› Output: 1
šŸ’” Note: The subarray [-1] has sum -1, and its absolute value 1 is the maximum absolute sum. We could also choose empty subarray with sum 0, but 1 > 0.
example_3.py — Single Element
$ Input: [2]
› Output: 2
šŸ’” Note: The only non-empty subarray is [2] with sum 2, so the maximum absolute sum is 2.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • Empty subarray is allowed with sum 0

Visualization

Tap to expand
Temperature Fluctuation AnalysisDaily Temperature Changes: [+1°, -3°, +2°, +3°, -4°]+1-3+2+3-4Hottest Period+2° + 3° = +5°Kadane's Algorithm Results:Maximum Sum: +5° (Days 3-4)Minimum Sum: -4° (Day 5)Most Extreme: max(|+5|, |-4|) = 5°
Understanding the Visualization
1
Track Maximum Heat
Use Kadane's algorithm to find the period with maximum positive temperature change
2
Track Maximum Cold
Use Kadane's algorithm to find the period with maximum negative temperature change
3
Compare Extremes
The most extreme period is whichever has the larger absolute temperature change
Key Takeaway
šŸŽÆ Key Insight: The maximum absolute sum is either the largest positive sum or the largest negative sum (in absolute terms) - Kadane's algorithm finds both efficiently!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
38.0K Views
Medium Frequency
~15 min Avg. Time
1.4K 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