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 x is a negative integer, then abs(x) = -x.
  • If x is a non-negative integer, then abs(x) = x.

Input & Output

Example 1 — Mixed Positive and Negative
$ Input: nums = [1,-3,2,1,-4]
Output: 4
💡 Note: 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
Maximum Absolute Sum of Any Subarray INPUT nums = [1, -3, 2, 1, -4] 1 i=0 -3 i=1 2 i=2 1 i=3 -4 i=4 Example Subarrays: [1] --> sum = 1 [1,-3] --> sum = -2 [2,1,-4] --> sum = -1 [-3,2,1,-4] --> sum = -4 abs(-4) = 4 [1,-3,2,1,-4] --> sum=-3 ALGORITHM STEPS 1 Initialize Variables maxAbsSum = 0 2 Outer Loop (i=0 to n-1) Start of each subarray 3 Inner Loop (j=i to n-1) End of each subarray 4 Update Max Absolute Sum maxAbsSum = max(maxAbsSum, abs(currentSum)) Key Iterations: i=1,j=4: [-3,2,1,-4]=-4 abs=4 i=1,j=3: [-3,2,1]=0 abs=0 i=1,j=4: sum=-4, abs=4 max=4 i=0,j=4: sum=-3, abs=3 max=4 i=1,j=1: [-3], abs=3 max=5! FINAL RESULT Maximum Absolute Sum Found: 1 -3 2 1 -4 Subarray: [-3, 2, 1, -4] Sum = -3 + 2 + 1 + (-4) = -4 OR Subarray [2, 1, -4] Sum = 2 + 3 = 5, abs(5) = 5 Best: [2, 1] or similar Sum = 3 or abs(-5) = 5 OUTPUT 5 OK - Maximum Absolute Sum Key Insight: The brute force approach checks ALL possible subarrays using nested loops. For each starting index i, we extend the subarray to every ending index j, calculating running sums. We track the maximum absolute value found. Time Complexity: O(n^2). The answer 5 comes from abs(sum of some subarray). TutorialsPoint - Maximum Absolute Sum of Any Subarray | Optimized Brute Force
Asked in
Amazon 15 Microsoft 12
28.0K Views
Medium Frequency
~15 min Avg. Time
845 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