Magicsheet logo

Maximum Absolute Sum of Any Subarray

Medium
12.5%
Updated 8/1/2025

Maximum Absolute Sum of Any Subarray

What is this problem about?

The Maximum Absolute Sum of Any Subarray problem asks you to find a contiguous sequence of elements within an integer array such that the absolute value of their sum is maximized. Because we are taking the absolute value, the optimal subarray could be one with a massive positive sum, OR one with a massive negative sum.

Why is this asked in interviews?

This is a direct, elegant extension of Kadane's Algorithm. Interviewers use it to see if a candidate understands how to adapt a standard Dynamic Programming template. It tests whether you recognize that tracking a running minimum is mathematically symmetrical to tracking a running maximum, and both can be executed simultaneously in a single linear pass.

Algorithmic pattern used

This problem leverages Kadane's Algorithm (Dynamic Programming). Since the absolute sum is maximized by either a very large positive number or a very "large" negative number (e.g., -100), we simply run Kadane's Algorithm twice simultaneously:

  1. Track the max_sum to find the largest positive subarray.
  2. Track the min_sum to find the smallest negative subarray. The final answer is exactly max(abs(max_sum), abs(min_sum)).

Example explanation

Array: [1, -3, 2, 3, -4] Let's track current_max, global_max and current_min, global_min.

  • Init all to 0.
  • 1:
    • curr_max = max(1, 0+1) = 1. global_max = 1.
    • curr_min = min(1, 0+1) = 1. global_min = 1.
  • -3:
    • curr_max = max(-3, 1-3) = -2. global_max = 1.
    • curr_min = min(-3, 1-3) = -3. global_min = -3.
  • 2:
    • curr_max = max(2, -2+2) = 2. global_max = 2.
    • curr_min = min(2, -3+2) = -1. global_min = -3.
  • 3:
    • curr_max = max(3, 2+3) = 5. global_max = 5.
    • curr_min = min(3, -1+3) = 2. global_min = -3.
  • -4:
    • curr_max = max(-4, 5-4) = 1. global_max = 5.
    • curr_min = min(-4, 2-4) = -4. global_min = -4.

At the end, global_max is 5 (subarray [2, 3]), global_min is -4 (subarray [-4]). Max absolute sum is max(abs(5), abs(-4)) = 5.

Common mistakes candidates make

A common error is trying to apply the absolute value operation on the elements before or during the running sum calculation (e.g., current_sum += abs(num)). This completely breaks the logic, as a negative number and a positive number in the same subarray would add up instead of canceling each other out. The absolute value must only be applied to the final aggregated global minimum and maximum sums.

Interview preparation tip

Another brilliant pattern to solve the Maximum Absolute Sum problem relies on Prefix Sums. If you compute the running prefix sum of the array, the maximum absolute subarray sum is simply max(prefix_sums) - min(prefix_sums). Mentioning this prefix sum trick to your interviewer demonstrates a highly advanced, overarching understanding of array mathematics.

Similar Questions