53最大子序和.py
题目:给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
来源:https://leetcode-cn.com/problems/maximum-subarray/solution/
法一:动态规划
思路:关键是要正确的写出状态转移方程.dp[i]表示的是以nums[i]结尾的最大子串和,注意不是nums[i]中的最大子串和,如果是nums[i]中的最大子串和,则状态转移方程较复杂,无法直接写出.
参考:https://leetcode-cn.com/problems/maximum-subarray/solution/dong-tai-gui-hua-jie-fa-4xing-pythondai-ma-by-mcdu/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from typing import List class Solution(): def maxSubArray(self, nums: List[int]) -> int: dp=nums[:] for i in range(1,len(nums)): dp[i]=max(dp[i-1]+nums[i],nums[i]) return max(dp) if __name__ == '__main__': duixiang = Solution() a = duixiang.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) print(a)
法二:官方解法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution: def maxSubArray(self, nums: 'List[int]') -> 'int': n = len(nums) max_sum = nums[0] for i in range(1, n): # 如果前一个数大于0,则加到当前数上, if nums[i - 1] > 0: nums[i] += nums[i - 1] # 否则是小于等于0,求该数与之前和的最大值. max_sum = max(nums[i], max_sum) return max_sum
yyy