Maximum Ascending Subarray Sum
Easy
Topics
Given an array nums, return the maximum possible sum of a strictly ascending contiguous subarray.
Example 1
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
Input: nums = [10,20,30,40,50] Output: 150
Example 3
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
current = best = nums[0].- For each later element: if it exceeds its predecessor, add it to
current; otherwise setcurrentto it. - 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 65Complexity
- Time — O(n): one pass.
- Space — O(1): two accumulators.
Common Pitfalls
- Resetting
currentto 0 rather than tonums[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
bestto 0. All values are positive here, so it happens to work, but initialising fromnums[0]is what makes it correct in general. - Updating
bestonly 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 bestimport java.util.*;
class Solution {
public int maxAscendingSum(int[] nums) {
int best = nums[0], cur = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = nums[i] > nums[i-1] ? cur + nums[i] : nums[i];
best = Math.max(best, cur);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxAscendingSum(vector<int>& nums) {
int best = nums[0], cur = nums[0];
for (int i = 1; i < (int)nums.size(); i++) {
cur = nums[i] > nums[i-1] ? cur + nums[i] : nums[i];
best = max(best, cur);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxAscendingSum = function(nums) {
let best = nums[0], cur = nums[0];
for (let i = 1; i < nums.length; i++) {
cur = nums[i] > nums[i-1] ? cur + nums[i] : nums[i];
if (cur > best) best = cur;
}
return best;
};