剑指 Offer 42. 连续子数组的最大和
1.题目
2.我的解决方案
- 这道题之前做过,还有点印象,果然刷题是有用的
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
res_max = -math.inf
pre = 0 # 用来保存正在尝试中的连续和
for i in range(len(nums)):
pre = max(nums[i], pre+nums[i]) # 判断nums[i]是加入连续数列,还是独立出来作为新的连续数列的开端
res_max = max(res_max, pre) # 更新最大值
return res_max
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)