NeetCode #50LC-1800EasyArrays & Hashing
← Back to All Problems#50 · #1800 · Maximum Ascending Subarray Sum(最大升序子数组和)
📌 Problem Statement & Constraints
Given an array of positive integers
nums, return the maximum possible sum of an ascending subarray: a contiguous run of elements where each is strictly greater than the previous. Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 100.💡 Core Algorithmic Approaches
- This is the maximum-run template with a sum instead of a length.
- Maintain
cur, the sum of the current ascending run, andbest. - If
nums[i] > nums[i-1], extend the run:cur += nums[i]. Otherwise restart the run atnums[i]. - Update
bestafter every step. Because all values are positive, restarting is always better than carrying a broken run forward.
💻 Benchmark Python3 Implementation
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
best = cur = nums[0]
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
cur += nums[i] # extend the ascending run
else:
cur = nums[i] # restart
best = max(best, cur)
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two accumulators.
⚠️ Interview Pitfalls & Follow-ups
- Initialising
curto 0:[5]should return 5, not 0. - Using
>=: the run must be strictly ascending. - Carrying the run across a break: resetting to
nums[i](not 0) is required, since the current element itself starts a new run. - Assuming positivity is needed for the greedy: it is what guarantees that a longer run is always at least as good, which is why the simple restart works.