Max Sum (O(n)时间复杂度)

Max Sum


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

// 设Si = A1 + A2 + A3 +...+Ai, 则 Ai + Ai+1 +...+ Aj = Sj - Si-1 (连续子序列之和等于两个前缀和之差)
// 当j确定时, “S[j] - S[i-1]最大” 相当于 “S[i-1]最小”,因此只需要扫描一次数组,维护“目前遇到过的最小的S”即可。
// 
#include 
#include 
using namespace std;

void Find(vector& a)
{
	vector s;
	int min = 0; //最小的子串和
	int start = 1, end = 1; //最大子串的开始位置和结束位置
	int min_position = 1; //目前最大字串和的开始位置
	int best = a[1];//将最大字串和初始化为第一个数字
	s.push_back(0);//由于序列是从一开始的,而我是用的向量存储,所以需要填入一个数字占位
	for (int i = 1; i < a.size(); i++)
	{
		s.push_back(s[i - 1] + a[i]);
		if (s[i - 1] < min) {
			min_position = i;
			min = s[i - 1];
		}
		if (best < s[i] - min) // 遇到最大字串和,将起始和终止的位置标好
		{
			best = s[i] - min;
			end = i;
			start = min_position;
		}
	}
	cout << best << " " << start << " " << end;
}

int main()
{
	//freopen("data.txt", "r", stdin);
	int T;
	int N;
	int num;
	vector array;
	cin >> T;
	array.push_back(0);
	for (int i = 0; i < T; i++)
	{
		cin >> N;
		for (int i = 0; i < N; i++) {
			cin >> num;
			array.push_back(num);
		}
		cout << "Case " << i + 1 << ":" << endl;
		Find(array);
		if (i != T - 1)
			cout << endl << endl;
		else
			cout << endl;
		array.clear();
		array.push_back(0);
	}
	return 0;
}




你可能感兴趣的:(HDOJ)