牛客网-连续子树组的最大和-动态规划
题目描述
求连续子向量的最大和。
{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和。(子向量的长度至少是1)
思路:
(1)自己做的
1.设两个指针,start和end只要s-e的和大于0,表示值可取,移动e指针,并加一个变量记录最大值
2.若值小于0,则移动s和e指针
(2)动态规划(参考)链接:https://www.nowcoder.com/questionTerminal/459bd355da1549fa8a49e350bf3df484?f=discussion
dp[i]表示以元素array[i]结尾的最大连续子数组和.
以[-2,-3,4,-1,-2,1,5,-3]为例
可以发现,
dp[0] = -2
dp[1] = -3
dp[2] = 4
dp[3] = 3
以此类推,会发现
dp[i] = max{dp[i-1]+array[i],array[i]}.
代码:
1.指针移动
# -*- coding:utf-8 -*- class Solution: def FindGreatestSumOfSubArray(self, array): # write code here result = array[0] fin = result start = 0 end = 1 while(start<=end and end<len(array)): result += array[end] if(result<=0): if(result>fin): fin = result result = 0 start = end+1 end = start continue if(result>fin): fin = result end += 1 return fin
2.动态规划
class Solution: def FindGreatestSumOfSubArray(self, array): # write code here dp = [i for i in array] for i in range(1,len(array)): dp[i] = max(dp[i-1]+array[i],array[i]) return max(dp)