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
xis a negative integer, thenabs(x) = -x. - If
xis a non-negative integer, thenabs(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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code