LeetCode 1749: Maximum Absolute Sum of Any Subarray Solution

Master LeetCode problem 1749 (Maximum Absolute Sum of Any Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1749. Maximum Absolute Sum of Any Subarray

Problem Explanation

Explanation

To solve this problem, we can use Kadane's algorithm twice. We can find the maximum subarray sum and minimum subarray sum by iterating through the array from left to right and then from right to left. The maximum absolute sum will be the maximum of these two values.

  1. Initialize variables maxSum and minSum as the first element of the array nums.
  2. Iterate through the array from left to right and update maxSum and minSum accordingly.
  3. Iterate through the array from right to left and update maxSum and minSum accordingly.
  4. Return the maximum of maxSum and minSum.

Time complexity: O(n) where n is the length of the input array nums. Space complexity: O(1)

Solution Code

class Solution {
    public int maxAbsoluteSum(int[] nums) {
        int maxSum = nums[0];
        int minSum = nums[0];
        int currentMax = nums[0];
        int currentMin = nums[0];
        
        for (int i = 1; i < nums.length; i++) {
            currentMax = Math.max(nums[i], currentMax + nums[i]);
            maxSum = Math.max(maxSum, currentMax);
            currentMin = Math.min(nums[i], currentMin + nums[i]);
            minSum = Math.min(minSum, currentMin);
        }
        
        return Math.max(Math.abs(maxSum), Math.abs(minSum));
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1749 (Maximum Absolute Sum of Any Subarray)?

This page provides optimized solutions for LeetCode problem 1749 (Maximum Absolute Sum of Any Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1749 (Maximum Absolute Sum of Any Subarray)?

The time complexity for LeetCode 1749 (Maximum Absolute Sum of Any Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1749 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1749 in Java, C++, or Python.

Back to LeetCode Solutions