Max Sum
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
题目链接:
题意描述:
这个题题意很简单,就是找一段连续的数字,要求它们的和最大,并输出该段数字的首尾下标。
解题思路:
我是先把它们存到数组中,存的过程中找到这n个数字的最大值如果最大值是小于等于0,那么就直接输出该数及其下标,否则就进行数字的累加,如果累加的和小于0了那么就把sum置为0,并暂时记录此刻的下标加1(加1的原因是该下标的值一定小于0,故暂且记录下一个下标暂为首下标),直到sum大于maxn更新maxn以及首尾下标。
程序代码:
这个代码我感觉有点麻烦,如果谁有简单一点的欢迎评论。
#include<stdio.h>
#include<string.h>
const int inf=99999999;
int a[100010];
int main()
{
int T,i,n,m,f,f0,e,maxn,sum,count=1;
scanf("%d",&T);
while(T--)
{
maxn=-inf;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]>maxn)
{
f=i;
e=i;
maxn=a[i];
}
}
if(maxn<=0)
printf("Case %d:\n%d %d %d\n",count++,maxn,f,e);
else
{
f0=1;
f=1;
e=1;
sum=0;
maxn=0;
for(i=1;i<=n;i++)
{
sum+=a[i];
if(sum<0)
{
f0=i+1;
sum=0;
}
if(sum>maxn)
{
maxn=sum;
f=f0;
e=i;
}
}
printf("Case %d:\n%d %d %d\n",count++,maxn,f,e);
}
if(T>0)
printf("\n");
}
return 0;
}