1749. Maximum Absolute Sum of Any Subarray LeetCode Solution

In this guide, you will get 1749. Maximum Absolute Sum of Any Subarray LeetCode Solution with the best time and space complexity. The solution to Maximum Absolute Sum of Any Subarray problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Maximum Absolute Sum of Any Subarray solution in C++
  4. Maximum Absolute Sum of Any Subarray solution in Java
  5. Maximum Absolute Sum of Any Subarray solution in Python
  6. Additional Resources
1749. Maximum Absolute Sum of Any Subarray LeetCode Solution image

Problem Statement of Maximum Absolute Sum of Any Subarray

You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, …, numsr-1, numsr] is abs(numsl + numsl+1 + … + numsr-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 negative integer, then abs(x) = -x.
If x is a non-negative integer, then abs(x) = x.

Example 1:

Input: nums = [1,-3,2,3,-4]
Output: 5
Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.

Example 2:

Input: nums = [2,-5,1,-4,3,-2]
Output: 8
Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

1749. Maximum Absolute Sum of Any Subarray LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

1749. Maximum Absolute Sum of Any Subarray LeetCode Solution in Java

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;
  }
}
// code provided by PROGIEZ

1749. Maximum Absolute Sum of Any Subarray LeetCode Solution in Python

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
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.