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.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
最大升序子数组和
给你一个正整数组成的数组 nums,返回 nums 中一个 升序子数组 的最大可能元素和。子数组是数组中的一个连续数字序列。注意:长度为 1 的子数组视为升序子数组。约束:1 ≤ nums.length ≤ 100;1 ≤ nums[i] ≤ 100。
核心要点
- 滚动和一次遍历(标准解) :维护当前升序段的累加和 cur。若 nums[i] > nums[i-1] 则 cur += nums[i] ,否则开启新段 cur = nums[i] 。每步更新 best。
- 与「最大子数组和」的区别 :本题的段边界由「是否升序」 硬性决定 ,不能用 Kadane 的「舍弃负数前缀」策略;因为所有元素都是正数,累加只会变大。
- 为什么不能简单取全部元素之和 :升序段必须是 连续且严格递增 的,遇到下降就必须断开。
- 初始值 :cur 与 best 都初始化为 nums[0] ,因为数组至少有一个元素。
常见陷阱
- 用 Kadane 的思路在遇到「负贡献」时重置 :本题所有元素为正,没有负贡献,重置条件只能是「不再升序」。套用 Kadane 会得到错误结果。
- 误以为可以跳过中间元素 :子数组必须连续,不能跳过导致下降的元素。
- 初始值设为 0 :若数组只有负数(本题约束下不会)会出错;本题约束 nums[i] ≥ 1,初值设为 nums[0] 是最稳妥的写法。
参考实现
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] # 延续升序段
else:
cur = nums[i] # 开启新段
if cur > best:
best = cur
return best