Code Logo

Maximum Ascending Subarray Sum

Published at24 Jul 2026
Easy 0 views
Like0

Given an array of integers nums, find the maximum possible sum of an ascending subarray where each element is strictly greater than the previous one. An ascending subarray is a contiguous segment where every adjacent pair is strictly increasing. A subarray of length 1 is always ascending.

This DP problem tracks the current ascending sum and the maximum sum seen so far. Start with the first element as both curSum and maxSum. For each subsequent element, if it is greater than the previous, extend the ascending run by adding it to curSum. Otherwise, reset curSum to the current element. Update maxSum at each step when curSum exceeds it.

The DP recurrence is: if nums[i] > nums[i-1], curSum += nums[i]; else curSum = nums[i]. Then maxSum = max(maxSum, curSum). Time is O(n) with O(1) space by using only two variables for the state.

Edge cases include an empty array (return 0), a single element (return that element), all elements decreasing (each element forms its own subarray, so max is the largest element), and strictly increasing (the entire array sums to the total).

The ascending subarray sum problem is a simple DP that demonstrates how tracking a single state variable (current ascending sum) can efficiently solve problems with sequential dependencies. It is a building block for more complex subsequence problems.

Example Input & Output

Example 1
Input
[10,20,30,40,50]
Output
150
Explanation

All ascending.

Example 2
Input
[]
Output
0
Explanation

Empty.

Example 3
Input
[10,20,30,5,10,50]
Output
65
Explanation

60 then 65.

Example 4
Input
[12,17,15,13,10,19,20]
Output
49
Explanation

End run 49.

Example 5
Input
[5]
Output
5
Explanation

Single.

Algorithm Flow

Recommendation Algorithm Flow for Maximum Ascending Subarray Sum
Recommendation Algorithm Flow for Maximum Ascending Subarray Sum

Solution Approach

Track curSum and maxSum. If ascending, extend; else reset. Update max.

function solution(nums) {
  if (nums.length === 0) return 0;
  var maxSum = nums[0], curSum = nums[0];
  for (var i = 1; i < nums.length; i++) {
    if (nums[i] > nums[i-1]) curSum += nums[i];
    else curSum = nums[i];
    if (curSum > maxSum) maxSum = curSum;
  }
  return maxSum;
}

Time O(n), Space O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        if (nums.length==0) return 0;
        int m=nums[0],c=nums[0];
        for (int i=1;i<nums.length;i++) {
            if (nums[i]>nums[i-1]) c+=nums[i];
            else c=nums[i];
            if (c>m) m=c;
        }
        return m;
    }
}