【PAT】1-2 Maximum Subsequence Sum

题目地址:http://www.patest.cn/contests/mooc-ds/01-2

计算最大子列和,并打印出子列的第一个元素和最后一个元素

#include <cstdio>

using namespace std;

#define MAXN 100000
int main()
{
	int list[MAXN];
	int n,i;

	int ThisSum, MaxSum;
	int head,tail;


	scanf("%d",&n);
    int start = 0,end = n-1;
    
	for (int i = 0; i < n; ++i)
	{
		scanf("%d",&list[i]);
	}	
        ThisSum = MaxSum = 0;
        for (int i = 0; i < n; ++i)
        {
    	    if (ThisSum >=0)
    	    {
    		   ThisSum += list[i];
    		   tail = i;
               
    	   }else
    	   {
    		ThisSum = list[i];
    		head = i;
    		tail = i;
    	    }
    	    if (ThisSum > MaxSum ||(ThisSum == 0 && MaxSum == 0))
    	    {
    	    	MaxSum = ThisSum;
    	    	start = head;
    	    	end = tail;
    	    }
         }
        printf("%d %d %d\n",MaxSum, list[start], list[end]);
	
    return 0;
}

  

 

posted @ 2015-01-27 15:38  Summer先生  阅读(122)  评论(0编辑  收藏  举报