PAT 1007 Maximum Subsequence Sum

#include<iostream>
using namespace std;

const int INF_MIN = 0x80000000;

bool isAllNeg(int a[], int n)
{
	int i = 0;
	for(i=0; i<n; i++)
		if(a[i] >= 0)
			return false;
	return true;
}

int findMaxSubSeq(int a[],int n,int &b,int &e)
{
	int max = INF_MIN;
	int i = 0;
	int t1 = a[0];
	int t2 = a[0];
	int sum = 0;
	for(i=0; i<n; i++)
	{
		t2 = a[i];
		sum += a[i];
		if(sum > max)
		{
			b = t1;
			e = t2;
			max = sum;
		}
		if(sum < 0)
		{
			sum = 0;
			if(i < n-1)
				t1 = a[i+1];
				t2 = a[i+1];
		}
	}
	return max;
}

int main()
{
	int a[10000],n,i,b,e;
	scanf("%d",&n);
	for(i=0; i<n; i++)
		scanf("%d",&a[i]);
	if(isAllNeg(a,n))
	{
		cout<<0<<" "<<a[0]<<" "<<a[n-1]<<endl;
	}
	else
	{
		int minSum = findMaxSubSeq(a,n,b,e);
		cout<<minSum<<" "<<b<<" "<<e<<endl;
	}
	
	return 0;
}

  

posted @ 2012-11-28 19:20  Frank@609  Views(391)  Comments(0Edit  收藏  举报