Maximum Ascending Subarray Sum

Easy

Topics
Array

Given an array nums, return the maximum possible sum of a strictly ascending contiguous subarray.

Example 1

10020130253104505sum = 65
The braced run is strictly ascending and contiguous, and has the largest sum, 65.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [10,20,30,5,10,50]
Output: 65

Example 2

100201302403504sum = 150
Input:  nums = [10,20,30,40,50]
Output: 150

Example 3

120171152133104115126sum = 33
Input:  nums = [12,17,15,13,10,11,12]
Output: 33

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

We want the largest sum over all strictly ascending runs. A run ends the moment an element fails to exceed its predecessor, so the array partitions into maximal ascending blocks and we want the heaviest block.

That means one pass with a running sum: extend it while the sequence keeps rising, and restart it at the current element when it does not. Restart at nums[i], not at 0 — the element that broke the old run is the first element of the new one.

Approach

  1. current = best = nums[0].
  2. For each later element: if it exceeds its predecessor, add it to current; otherwise set current to it.
  3. Track the maximum of current.

Dry Run

nums = [10,20,30,5,10,50]

10            current=10  best=10
20 > 10       current=30  best=30
30 > 20       current=60  best=60
5  < 30       current=5   best=60   (run broken, restart at 5)
10 > 5        current=15  best=60
50 > 10       current=65  best=65

answer 65

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two accumulators.

Common Pitfalls

  • Resetting current to 0 rather than to nums[i], which drops the first element of every new run.
  • Using >= for the ascending test. The problem says strictly ascending, so equal neighbours break the run.
  • Initialising best to 0. All values are positive here, so it happens to work, but initialising from nums[0] is what makes it correct in general.
  • Updating best only when a run ends, which misses a run that reaches the end of the array.

Full Solution — all languages

class Solution:
    def maxAscendingSum(self, nums):
        best = cur = nums[0]
        for i in range(1, len(nums)):
            cur = cur + nums[i] if nums[i] > nums[i-1] else nums[i]
            best = max(best, cur)
        return best
SensAI
Beta
Tap the mic to stop voice mode