Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Last active February 26, 2025 22:16
Show Gist options
  • Save Ifihan/e643bb77bbe1cae4c649abdb7a9c6a67 to your computer and use it in GitHub Desktop.
Save Ifihan/e643bb77bbe1cae4c649abdb7a9c6a67 to your computer and use it in GitHub Desktop.
Maximum Absolute Sum of Any Subarray

Question

Approach

I first initialized variables to track the maximum and minimum sums as well as the current sums while iterating through the array. At each step, I updated the current maximum and minimum sums by either extending the existing subarray or starting fresh with the current element. At the same time, I maintained the global maximum and minimum sums observed during the traversal.

Finally, I returned the greater value between the maximum sum and the absolute value of the minimum sum.

Implementation

class Solution:
    def maxAbsoluteSum(self, nums: List[int]) -> int:
        max_sum = 0
        min_sum = 0
        current_max = 0
        current_min = 0

        for num in nums:
            current_max = max(num, current_max + num)
            max_sum = max(max_sum, current_max)

            current_min = min(num, current_min + num)
            min_sum = min(min_sum, current_min)

        return max(max_sum, abs(min_sum))

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment