#1749

Maximum Absolute Sum of Any Subarray

Medium
ArrayDynamic ProgrammingKadane's AlgorithmDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages a modified version of Kadane's algorithm to find the maximum absolute sum efficiently. Instead of calculating the sum directly, we track both the maximum and minimum sums as we iterate through the array.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize variables to track the maximum and minimum sums as well as the current sum.
  2. 2Step 2: Iterate through the array, updating the current sum by adding the current element.
  3. 3Step 3: Update the maximum and minimum sums based on the current sum.
  4. 4Step 4: The maximum absolute sum is the maximum of the absolute values of the maximum and minimum sums.
solution.py14 lines
1# Full working Python code
2
3def maxAbsoluteSum(nums):
4    max_sum = 0
5    min_sum = 0
6    current_sum = 0
7    for num in nums:
8        current_sum += num
9        max_sum = max(max_sum, current_sum)
10        min_sum = min(min_sum, current_sum)
11    return max(abs(max_sum), abs(min_sum))
12
13# Example usage
14print(maxAbsoluteSum([1, -3, 2, 3, -4]))  # Output: 5

Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) as we are using a constant amount of space.

  • 1The maximum absolute sum can be derived from both the maximum and minimum sums of subarrays.
  • 2Using a single pass through the array allows us to efficiently track necessary sums.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.