Max Sum
*Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 236675 Accepted Submission(s): 55857*
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 4
Case 2:
7 1 6
这道题是用动态规划求得最大和子序列,子序列指的是连续的一组数列,不是断断续续的数列。
array[i]的值表示 以第i个数字为结尾的子序列的最大和
array[1];
array[2] = max{array[1]+array[2], array[1]};
array[3] = max{array[1]+array[2]+array[3], array[2]+array[3], array[3]};
array[4] = max{array[1]+array[2]+array[3]+array[4], array[2]+array[3]+array[4], array[3]+array[4], array[4]};
……
最后的最大和的值就是这里面的最大值。
简化一下,用一个变量maxSum来记录array计算运行当中的最大值,sum表示连续子序列的和,x和y表示起始点和终止点。
如果sum > maxSum,则maxSum=sum,并更新x和y的值;
如果sum < maxSum,表示当前的array值是负值,但是之后的数字可能会让sum值再次大于maxSum的值(相等同理);
如果sum<0,则舍弃这一段子序列,因为这一段子序列只会使整个序列的和减小,更新temp标志。
(注意 只有当sum>maxSum时才能更新x和y的值,也就是说temp标记更改之后可能并没有出现比maxSum还大的值)
#include <cstdio>
using namespace std;
#define MaxSize 100005
int arr[MaxSize];
int main()
{
int T;
scanf("%d",&T);
int cnt;
for(cnt=1; cnt<=T; cnt++)
{
int N,i;
scanf("%d",&N);
for(i=1; i<=N; i++)
{
scanf("%d",&arr[i]);
}
int maxSum=-100000,sum=0,x=1,y=1,temp=1;
for(i=1; i<=N; i++)
{
sum += arr[i];
if(sum > maxSum)
{
maxSum = sum;
x=temp;
y=i;
}
if(sum < 0)
{
sum = 0;
temp=1+i;
}
}
printf("Case %d:\n",cnt);
printf("%d %d %d\n",maxSum,x,y);
if(cnt<T)
printf("\n");
}
return 0;
}