- 注意加上之后为负的情况,重置cal为0
- 注意数组全部为负数的情况
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
# cal表示加到当前值为止能获得的结果
cal = 0
res = float("-inf")
for item in nums:
cal += item
# 先计算最大值再重置
res = max(res, cal)
# 如果cal小于0, 则说明加到当前值为止的数组可以抛弃掉,重新开始计算
if cal < 0:
cal = 0
return res