Maximum Ascending Subarray Sum
Easy · Arrays & Hashing · Explanation and code example
Iteration
How it works
We can solve this in a single pass. As we scan through the array, we maintain a running sum of the current ascending subarray. Whenever we encounter an element that does not continue the ascending pattern, we reset the running sum and start a new subarray from that element.
This works because ascending subarrays are naturally separated by positions where the ascending condition breaks.
Steps
- Initialize
res = nums[0]andcurSum = nums[0]. - For each index
ifrom1ton-1:- If
nums[i] <= nums[i-1], resetcurSum = 0. - Add
nums[i]tocurSum. - Update
res = max(res, curSum).
- If
- Return
res.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Using Non-Strict Inequality
The problem requires strictly ascending elements, meaning each element must be greater than the previous one. Using >= instead of > when checking the ascending condition will incorrectly include equal consecutive elements in your subarray, leading to wrong answers.
Forgetting Single-Element Subarrays
A single element by itself forms a valid ascending subarray. If you forget to consider this case or initialize your result incorrectly, you might miss the maximum when the answer is a single large element surrounded by non-ascending neighbors.
Python code example
from typing import List
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
res = curSum= nums[0]
for i in range(1, len(nums)):
if nums[i] <= nums[i - 1]:
curSum = 0
curSum += nums[i]
res = max(res, curSum)
return res
C++ code example
class Solution {
public:
int maxAscendingSum(vector<int>& nums) {
int res = nums[0], curSum = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] <= nums[i - 1]) {
curSum = 0;
}
curSum += nums[i];
res = max(res, curSum);
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.