https://leetcode.com/problems/maximum-subarray/#/description
说明
- 查找连续子数组,使之sum最大
思路
- 初始化maxSum = a[0], curSum = a[0]
- 如果 curSum > 0 则curSum = curSum + a[i]
- 如果 curSum < 0 则 curSum = a[i]
- maxSum = max(maxSum, curSum)
# Time O(n)
# Space O(1)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curSum = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
if curSum >= 0:
curSum = curSum + nums[i]
else:
curSum = nums[i]
maxSum = max(maxSum, curSum)
return maxSum