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
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!
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code