动态规划求最大连续子序列和
题目链接: Max Sum
Problem Description
Given a sequence a[1],a[2],a[3]…a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4Case 2:
7 1 6
题目大意
给定序列a[1]、a[2]、[3]…a[n],计算子序列的最大和。例如,给定(6,-1,5,4,-7),此序列中的最大和为6+(-1)+5+4=14。
解题思路
这个问题就是用动态规划求最大连续子序列和,令状态dp[i]表示以a[i]作为末尾的连续序列的最大和。以样例为例:序列 6 -1 5 4 -7,下标分别为0,1,2,3,4
dp[0]=6
dp[1]=5(6+(-1)=5)
dp[2]=10(6+(-1)+5=10)
dp[3]=14(6+(-1)+5+4=14)
dp[4]=7(6+(-1)+5+4+(-7)=7)
因为dp数组的含义,a[4]必须作为l连续序列的结尾,于是最大和不是6+(-1)+5+4=14,而是6+(-1)+5+4+(-7)=7
通过设置dp数组,要求的最大和就是dp[0],dp[1],dp[2],…,dp[n-1]中的最大值,那么问题就转化成如何求dp数组。
因为dp[i]要求是必须以a[i]结尾的连续序列,那么只有两种情况:
1.这个最大和的连续子序列只有一个元素,即以a[i]开始,a[i]结束
2.这个最大连续序列有多个元素,即从前面某处a[p]开始,一直到a[i]结束(p<i)
对于第一种情况,最大和就是a[i]本身。
对于第一种情况,最大和就是dp[i-1]+a[i],即a[p]+a[p&