Skip to main content
Back to problems
#1749
Medium Algorithms

Maximum absolute sum of any subarray

Array Dynamic Programming
71.2% acceptance
Feb 25, 2026
1988
49
You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr] is abs(numsl + numsl+1 + ... + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows: If x is a non-negative integer, then abs(x) = x. If x is a negative integer, then abs(x) = -x.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_absolute_sum(nums: Vec<i32>) -> i32 {
    let (mut max_sum, mut min_sum) = (0i32, 0i32);
    let (mut cur_max, mut cur_min) = (0i32, 0i32);
    for &n in &nums {
      cur_max = cur_max.max(0) + n;
      cur_min = cur_min.min(0) + n;
      max_sum = max_sum.max(cur_max);
      min_sum = min_sum.min(cur_min);
    }
    max_sum.max(-min_sum)
  }
}