Show problems as
Classic problem #1749MediumArrayDynamic Programming

Maximum Absolute Sum of Any Subarray

Real-world version: The Biggest Swing in a Run of Adjustments
Tracked in this browser only
Read Maximum Absolute Sum of Any Subarray on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A ledger of adjustments reads adjustments. A stretch is any run of neighbouring entries, and the empty stretch counts as one, with a total of nothing.

Return the largest size any stretch's total reaches, where size ignores whether the total came out above or below nothing.

Examples

Example 1

Input
adjustments = [4, -1, 2, 1]
Output
6

The whole ledger totals six, and no shorter stretch swings further in either direction.

Example 2

Input
adjustments = [-1, -2, -3]
Output
6

Every entry pulls downward, so the whole ledger's total of minus six is the furthest swing and its size is six.

Example 3

Input
adjustments = [10000, -10000, 10000]
Output
10000

Either of the two rises on its own swings ten thousand. Taking more entries only cancels part of the swing away.

Constraints

  • 1 <= adjustments.length <= 10^5
  • -10^4 <= adjustments[i] <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_absolute_sum(adjustments: list[int]) -> int:
Java
public int maxAbsoluteSum(int[] adjustments)