Maximum Ascending Subarray Sum
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
All ascending.
Empty.
60 then 65.
End run 49.
Single.
Algorithm Flow
Solution Approach
Find the maximum sum of a contiguous strictly increasing subarray. Iterate through the array, accumulating a running sum. When the current element is greater than the previous one, add it to the running sum. When it is not greater, reset the running sum to the current element. Track the maximum running sum seen.
The reset behavior handles decreasing or equal elements by starting a new subarray from that element. Each ascending run is evaluated independently, and the global maximum is tracked across all runs.
Time complexity is O(n), space complexity is O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
