LeetCode 题解工作台
最大升序子数组和
给你一个正整数组成的数组 nums ,返回 nums 中一个 严格递增子数组 的最大可能元素和。 子数组是数组中的一个连续数字序列。 示例 1: 输入: nums = [10,20,30,5,10,50] 输出: 65 解释: [5,10,50] 是元素和最大的升序子数组,最大元素和为 65 。 示…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们用变量 记录当前升序子数组的和,用变量 记录最大的升序子数组和。 遍历数组 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个正整数组成的数组 nums ,返回 nums 中一个 严格递增子数组 的最大可能元素和。
子数组是数组中的一个连续数字序列。
示例 1:
输入:nums = [10,20,30,5,10,50] 输出:65 解释:[5,10,50] 是元素和最大的升序子数组,最大元素和为 65 。
示例 2:
输入:nums = [10,20,30,40,50] 输出:150 解释:[10,20,30,40,50] 是元素和最大的升序子数组,最大元素和为 150 。
示例 3:
输入:nums = [12,17,15,13,10,11,12] 输出:33 解释:[10,11,12] 是元素和最大的升序子数组,最大元素和为 33 。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100
解题思路
方法一:直接模拟
我们用变量 记录当前升序子数组的和,用变量 记录最大的升序子数组和。
遍历数组 :
如果当前元素是数组的第一个元素,或者当前元素大于前一个元素,那么将当前元素加入到当前升序子数组的和,即 ,并且更新最大升序子数组和 ;否则,当前元素不满足升序子数组的条件,那么将当前升序子数组的和 重置为当前元素,即 。
遍历结束,返回最大升序子数组和 。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
ans = t = 0
for i, v in enumerate(nums):
if i == 0 or v > nums[i - 1]:
t += v
ans = max(ans, t)
else:
t = v
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The interviewer emphasizes contiguous subarray, which points to tracking runs instead of searching arbitrary subsequences.
- question_mark
The constraint that values are positive makes the running-sum reset logic especially straightforward when an ascending streak breaks.
- question_mark
A hint like "fast enough to check all possible subarrays" often tests whether you can notice the simpler one-pass property of maximal increasing runs.
常见陷阱
外企场景- error
Using >= instead of >, which incorrectly merges equal adjacent values into an ascending run.
- error
Thinking this is about the longest or maximum-sum increasing subsequence, even though the subarray must remain contiguous.
- error
Forgetting to update the best sum after extending a run, which can miss answers in a fully increasing array such as [10,20,30,40,50].
进阶变体
外企场景- arrow_right_alt
Return the actual ascending subarray with the maximum sum instead of only the sum, which requires tracking the run start and best segment bounds.
- arrow_right_alt
Change the rule to non-decreasing subarray sum, where the comparison becomes >= and equal neighbors no longer break the run.
- arrow_right_alt
Ask for the maximum product of a strictly increasing contiguous subarray, which changes the state update even though the run-breaking logic stays similar.