题目
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
思路
用dp[i]表示用nums[i]结尾的最大连续子序列和。
代码
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0 for i in range(len(nums))]
for i in range(len(nums)):
dp[i] = nums[i] if i == 0 else max(dp[i - 1] +nums[i], nums[i])
return max(dp)