Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1749: Maximum Absolute Sum of Any Subarray

LeetCode 1749 Solution 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)

LeetCode 1749 Solutions in Java, C++, Python

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));
    }
}

Interactive Code Editor for LeetCode 1749

Improve Your LeetCode 1749 Solution

Use the editor below to refine the provided solution for LeetCode 1749. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems