题目链接
https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/566/
解题思路
遍历数组逐个叠加,
如果出现叠加值为负,则更新为当前index值;
为正,则继续叠加。
同时,判断是否为目前最大和,若是,则更新最大值。
最终,返回记录的最大值。
代码
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxsum = oldsum = nums[0]
for i in range(1, len(nums)):
oldsum = nums[i] if oldsum <= 0 else oldsum + nums[i]
maxsum = max(maxsum, oldsum)
return maxsum