classSolution:defmaxSubArray(self,nums: List[int]) ->int: res =-sys.maxsizefor i inrange(len(nums)):for j inrange(i, -1, -1): res =max(res, sum(nums[j:i+1]))return res
解法二:dp
摘自《计算机算法设计与分析》王晓东 第3版
classSolution:defmaxSubArray(self,nums: List[int]) ->int:sum= nums[0]#初始累加和 b = nums[0]#dp初始状态,0号for i inrange(1, len(nums)):#从1号开始if b >0: b += nums[i]else: b = nums[i]sum=max(b, sum)returnsum
2020.3.29
classSolution:defmaxSubArray(self,nums: List[int]) ->int: n =len(nums) dp = [0] * n res = nums[0]if n ==1:return res dp[0]= nums[0]#初始#用dp[i]记录0~i处最大子序和(包括i)for i inrange(1, n):if dp[i-1]<0:#若前面的和小于0,则舍弃 dp[i]= nums[i]else: dp[i]= dp[i-1]+ nums[i] res =max(res, dp[i])#更新最大和return res
classSolution:defmaxSubArray(self,nums) ->int: n =len(nums)if n ==0:return0if n ==1:return nums[0] dp = [0] * n dp[0]= nums[0]# 初始 res = dp[0]for i inrange(1, n): dp[i]=max(nums[i], dp[i -1] + nums[i]) res =max(res, dp[i])return res
改进:状态压缩 由于迭代过程中只用到dp[i-1]和dp[i],用dp_0和dp_1代替节省空间
classSolution:defmaxSubArray(self,nums) ->int: n =len(nums)if n ==0:return0if n ==1:return nums[0] dp = [0] * n dp_0 = nums[0]# 初始 res = dp_0for i inrange(1, n): dp_1 =max(nums[i], dp_0 + nums[i]) dp_0 = dp_1 res =max(res, dp_0)return res