Maximum Absolute Sum of Any Subarray

medium dynamic programming kadane array

Problem

Given an integer array nums, the absolute sum of a subarray is the absolute value of the sum of its elements. Return the maximum absolute sum over all (possibly empty) subarrays. Since the empty subarray sums to 0, the answer is never negative.

Inputnums = [1,-3,2,3,-4]
Output5
The subarray [2,3] has absolute sum abs(2+3) = 5, the largest possible.
Inputnums = [2,-5,1,-4,3,-2]
Output8
The subarray [-5,1,-4] has absolute sum abs(-8) = 8.

def maxAbsoluteSum(nums):
    max_sum = min_sum = 0
    cur_max = cur_min = 0
    for x in nums:
        cur_max = max(cur_max + x, 0)
        cur_min = min(cur_min + x, 0)
        max_sum = max(max_sum, cur_max)
        min_sum = min(min_sum, cur_min)
    return max(max_sum, -min_sum)
function maxAbsoluteSum(nums) {
  let maxSum = 0, minSum = 0;
  let curMax = 0, curMin = 0;
  for (const x of nums) {
    curMax = Math.max(curMax + x, 0);
    curMin = Math.min(curMin + x, 0);
    maxSum = Math.max(maxSum, curMax);
    minSum = Math.min(minSum, curMin);
  }
  return Math.max(maxSum, -minSum);
}
int maxAbsoluteSum(int[] nums) {
    int maxSum = 0, minSum = 0;
    int curMax = 0, curMin = 0;
    for (int x : nums) {
        curMax = Math.max(curMax + x, 0);
        curMin = Math.min(curMin + x, 0);
        maxSum = Math.max(maxSum, curMax);
        minSum = Math.min(minSum, curMin);
    }
    return Math.max(maxSum, -minSum);
}
int maxAbsoluteSum(vector<int>& nums) {
    int maxSum = 0, minSum = 0;
    int curMax = 0, curMin = 0;
    for (int x : nums) {
        curMax = max(curMax + x, 0);
        curMin = min(curMin + x, 0);
        maxSum = max(maxSum, curMax);
        minSum = min(minSum, curMin);
    }
    return max(maxSum, -minSum);
}
Time: O(n) Space: O(1)