Maximum Absolute Sum of Any Subarray (LeetCode 1749): Solution and Explanation
Find the subarray whose sum is furthest from zero, in either direction, and return that distance. The empty subarray counts and has sum 0. For [1,-3,2,3,-4] the answer is 5, from the subarray [2,3].
Intuition
The winning subarray either has the largest sum or the most negative sum, so you need both. Running Kadane's algorithm twice works, but there is a neater view.
Write P[k] for the sum of the first k elements, with P[0] = 0. The sum of nums[l..r] is P[r + 1] - P[l], the gap between two points on the prefix-sum curve.
The biggest absolute gap between any two points of a curve is its highest point minus its lowest point. Their order does not matter because of the absolute value, so one pass tracking the max and min prefix is enough.
Approach: Highest prefix minus lowest prefix
- Set
prefix,hiandloto 0. Starting both bounds at 0 counts the empty prefix. - For each
xinnums, add it toprefix. - Update
hi = max(hi, prefix)andlo = min(lo, prefix). - Return
hi - lo.
Step-by-step example
nums = [1,-3,2,3,-4]
- Start with prefix = 0, hi = 0, lo = 0.
- Add 1: prefix = 1, new peak hi = 1. Add -3: prefix = -2, new valley lo = -2.
- Add 2: prefix = 0, inside the band. Add 3: prefix = 3, new peak hi = 3.
- Add -4: prefix = -1, inside the band.
- Answer = 3 - (-2) = 5. The valley is P[2] and the peak is P[4], so the subarray is nums[2..3] = [2,3].
Code: Python, Java, C++
1class Solution:
2 def maxAbsoluteSum(self, nums: List[int]) -> int:
3 prefix = hi = lo = 0
4 for x in nums:
5 prefix += x
6 hi = max(hi, prefix)
7 lo = min(lo, prefix)
8 return hi - lo1class Solution {
2 public int maxAbsoluteSum(int[] nums) {
3 int prefix = 0, hi = 0, lo = 0;
4 for (int x : nums) {
5 prefix += x;
6 hi = Math.max(hi, prefix);
7 lo = Math.min(lo, prefix);
8 }
9 return hi - lo;
10 }
11}1class Solution {
2public:
3 int maxAbsoluteSum(vector<int>& nums) {
4 int prefix = 0, hi = 0, lo = 0;
5 for (int x : nums) {
6 prefix += x;
7 hi = max(hi, prefix);
8 lo = min(lo, prefix);
9 }
10 return hi - lo;
11 }
12};Time and space complexity
O(n)
One pass with constant work per element.
O(1)
Only three running numbers are kept.
Other approaches
Kadane twice (time O(n), space O(1))
Track the best sum ending here (reset at 0 when it goes negative) and the worst sum ending here (reset at 0 when it goes positive). Return the larger of the best maximum and the absolute value of the best minimum.
All pairs of endpoints (time O(n^2), space O(n))
Compute prefix sums and compare every pair. Correct but quadratic, far too slow for 10^5 elements.
Common mistakes
- Starting
hiandloat the first element instead of 0. The empty prefix P[0] = 0 is a valid endpoint, and leaving it out breaks inputs like[5]. - Insisting that the peak comes before the valley. The absolute value makes either order fine.
- Only running max-subarray Kadane. An array like
[-1,-2,-3,-4]needs the negative side.
Frequently asked questions
Can the answer overflow a 32-bit integer?
No. At most 10^5 elements of absolute value 10^4 give a gap of at most 10^9.
How do I recover the subarray itself?
Remember the prefix indices where hi and lo were reached. The subarray runs between those two indices, from the smaller one to the larger one minus 1.
Why is this filed under dynamic programming?
The common solution is Kadane's algorithm, a one-dimensional DP over the best sum ending at each index. The prefix-sum view is the same idea with the state folded into two numbers.