Skip to content

1749. Maximum Absolute Sum of Any Subarray 👍

Approach 1: Kadane's

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxAbsoluteSum(vector<int>& nums) {
    int ans = INT_MIN;
    int maxSum = 0;
    int minSum = 0;

    for (const int num : nums) {
      maxSum = max(num, maxSum + num);
      minSum = min(num, minSum + num);
      ans = max({ans, maxSum, -minSum});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maxAbsoluteSum(int[] nums) {
    int ans = Integer.MIN_VALUE;
    int maxSum = 0;
    int minSum = 0;

    for (final int num : nums) {
      maxSum = Math.max(num, maxSum + num);
      minSum = Math.min(num, minSum + num);
      ans = Math.max(ans, Math.max(maxSum, -minSum));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxAbsoluteSum(self, nums):
    ans = -math.inf
    maxSum = 0
    minSum = 0

    for num in nums:
      maxSum = max(num, maxSum + num)
      minSum = min(num, minSum + num)
      ans = max(ans, maxSum, -minSum)

    return ans

Approach 2: Heuristic

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxAbsoluteSum(vector<int>& nums) {
    int sum = 0;
    int maxPrefix = 0;
    int minPrefix = 0;

    for (const int num : nums) {
      sum += num;
      maxPrefix = max(maxPrefix, sum);
      minPrefix = min(minPrefix, sum);
    }

    return maxPrefix - minPrefix;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maxAbsoluteSum(int[] nums) {
    int sum = 0;
    int maxPrefix = 0;
    int minPrefix = 0;

    for (final int num : nums) {
      sum += num;
      maxPrefix = Math.max(maxPrefix, sum);
      minPrefix = Math.min(minPrefix, sum);
    }

    return maxPrefix - minPrefix;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxAbsoluteSum(self, nums):
    summ = 0
    maxPrefix = 0
    minPrefix = 0

    for num in nums:
      summ += num
      maxPrefix = max(maxPrefix, summ)
      minPrefix = min(minPrefix, summ)

    return maxPrefix - minPrefix