def maxSubArray(nums):
'''
求最大子串和
'''
# print(len(nums))
# 如果该串长度为一,和最大的子串就是本身
if len(nums)==1:
return nums[0]
# 用来存放每次更新的最大子串和
max_ret = nums[0]
cur_max = last_max = nums[0]
# 状态转移方程,一步步的分解子问题
for i in range(1,len(nums)):
if last_max+nums[i] < nums[i]:
cur_max = nums[i]
else:
cur_max = last_max+nums[i]
if cur_max > max_ret:
max_ret = cur_max
last_max = cur_max
return max_ret
list01=[2,-5,-6,-8,-3,3,56,6,3,6,7,100,9,3]
# list01=[1,2,3,-1]
print(maxSubArray(nums=list01))
# 算法复杂度为O(N),(需要循环遍历整个串)
python 动态规划题------求最大连续子串和
猜你喜欢
转载自blog.csdn.net/qq_41228218/article/details/103836569
今日推荐
周排行