题目链接:
https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/
题意:
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
题解:
遍历一次,当当前子区间的和小于0则舍弃掉当前子区间,新开一个区间。过程中维护最大值即可。
注意最大值初始化
代码:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
ans,tmp = nums[0],0
for x in nums:
tmp+=x
ans=max(ans,tmp)
if tmp<0:
tmp=0
return ans