Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 4, 2025 22:48
Show Gist options
  • Save Ifihan/e2dfc923b3193d7f78f379da14d2938a to your computer and use it in GitHub Desktop.
Save Ifihan/e2dfc923b3193d7f78f379da14d2938a to your computer and use it in GitHub Desktop.
Maximum Ascending Subarray Sum

Question

Approach

My approach started with two variables: max_sum to store the highest sum found and current_sum to keep track of the running sum of the current ascending subarray. Starting with the first element, I iterated through the array. If the current number is greater than the previous one, I will add it to current_sum. Otherwise, I will update max_sum if current_sum is larger, then reset current_sum to the current number.

At the end of the loop, I will return the maximum of max_sum and current_sum to account for the last subarray.

Implementation

class Solution:
    def maxAscendingSum(self, nums: List[int]) -> int:
        max_sum = 0
        current_sum = nums[0]
        
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                current_sum += nums[i]
            else:
                max_sum = max(max_sum, current_sum)
                current_sum = nums[i]
        
        return max(max_sum, current_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