Maximum Absolute Sum of Any Subarray

You are given an integer array `nums`. The absolute sum of a subarray `[nums[l], ..., nums[r]]` is `abs(nums[l] + ... + nums[r])`. Return the maximum absolute sum of any (possibly empty) subarray of `nums`. The empty subarray has sum 0.

30:00

Maximum Absolute Sum of Any Subarray
medium
Free written solution
Topics
Companies

You are given an integer array nums. The absolute sum of a subarray [nums[l], ..., nums[r]] is abs(nums[l] + ... + nums[r]). Return the maximum absolute sum of any (possibly empty) subarray of nums. The empty subarray has sum 0.

Example 1:
Input: {"nums":[1,-3,2,3,-4]}
Output: 5
Constraints:
  • 1≤nums.length≤1051 \leq nums.\text{length} \leq 10^5

  • −104≤nums[i]≤104-10^4 \leq nums[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,-3,2,3,-4]}
1

0

-3

1

2

2

3

3

-4

4

prefix sums P[0..5] (P[0] = 0, the empty prefix)

0
hi 0 @P[0]lo 0 @P[0]gap 0

Any subarray sum is P[r] - P[l] for two prefix sums. The largest |P[r] - P[l]| is simply the highest prefix minus the lowest, so track both, starting from the empty prefix 0.

Variables
VariableValue
prefix0
hi0
lo0
DepthFunction Call
Stack empty
0/7