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 4
Case 2:
7 1 6
个人分析:
这个题目意思就是求最大连续子序列和,并且还要确定你取的数字起始位置和结束位置(从1开始计数)所以我们后面的得到的结果要+1 核心代码如下:
if(sum+a[i]>=a[i])
{
sum+=a[i];
last=i;
}
else
{
sum=a[i];
first=last=i;
}
对以上代码的解释:
状态转移方程,max( dp[ i - 1 ] + a [ i ] , a [ i ] )
从这个状态转移方程,我们就可以想到:
相加后大于该点的值,则加入当前连续段,更新该点为终点
相加后小于该点的值,则结束当前连续段,更新该点为起点、终点
其实这样相当于求出了很多个sum值,然后通过中间变量ans比较 找到那个最大的sum赋值给ans 然后输出ans
个人感受:
我看别人大佬的博客代码里面有两个数组,多了一个dp数组,很明显这个题要用动态规划才能解。但是后面想了想觉得没必要两个数组,具体看分析~
具体代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100000+8,INF=0x7f7f7f7f;
int a[maxn];
int main()
{
int t,k=0;
cin>>t;
while(t--)
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int sum=0,ans=-INF;
int first=0,last=0;
int x=0,y=0;
for(int i=0;i<n;i++)
{
if(sum+a[i]>=a[i])
{
sum+=a[i];
last=i;
}
else
{
sum=a[i];
first=last=i;
}
if(sum>ans)
{
ans=sum;
x=first;
y=last;
}
}
printf("Case %d:\n",++k);
printf("%d %d %d\n",ans,x+1,y+1);
if(t)
{
cout<<endl;
}
}
return 0;
}
学如逆水行舟,不进则退