Leetcode53-最大子序和
思路:动态规划
dp[i]指i处的最大子序和,如果dp[i-1]<0, 那么dp[i-1]+nums[i]肯定比nums[i]小,此时舍弃dp[i-1],dp[i] = nums[i]
代码:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
if dp[i-1] < 0:
dp[i] = nums[i]
else:
dp[i] = dp[i-1] + nums[i]
return max(dp)