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.
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))
- Time: O(n)
- Space: O(1)
