Maximum Subsequence Sum浙大数据结构

来源:互联网 发布:青年网络公开课 2017 编辑:程序博客网 时间:2024/06/06 17:20

Maximum Subsequence Sum

Given a sequence of K integers { N1N2, ..., NK }. A continuous subsequence is defined to be {NiNi+1, ..., Nj } where 1ijK. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4
#include<stdio.h>int main(){int a[10000];int K;//输入数据的个数 int Thissum=0,Maxsum=0; //Thissum当前子列和,Maxsum最大的子列和 int i; int posiflag=0;//检测是否有正数 int mleft=0,mright=0;//mleft是最大子列的第一个数,mright为最后一个数 int left=0;//left是中间变量,代表原来子列不符合要求,//要去找新的子列的第一个数 int left_flag=1;scanf("%d",&K);for(i=0;i<K;i++)scanf("%d",&a[i]);for(i=0;i<K;i++){Thissum+=a[i];if(a[i]>=0)posiflag=1;//输入的数据有正数,就置1 if(left_flag){left=a[i]; left_flag=0;}if(Thissum>Maxsum){//当前子列和最大,Maxsum更新 Maxsum=Thissum;mleft=left;//最大子列的第一个数就是当前子列的第一个数 mright=a[i];//最大子列的最后一个数就是当前子列的最后一个数}else if(Thissum<0){//Thissum<0时,要放弃原来的子列(和为负,已经不能使后面的数增大了),//所以去找新的子列 。 Thissum=0;//重新置为0 left_flag=1;//left_flag置1,因为循环,还没有指向下一个数。//所以left的修改放在下一次循环里 //left的值将会为下一个子列的第一个数 }}if(posiflag)printf("%d %d %d",Maxsum,mleft,mright);elseprintf("%d %d %d",Maxsum,a[0], a[K-1]);return 0;}



原创粉丝点击