1. 程式人生 > >PAT--1007 Maximum Subsequence Sum (25 分)

PAT--1007 Maximum Subsequence Sum (25 分)

1007 Maximum Subsequence Sum (25 分)

Given a sequence of K integers { N​1, N​2​​ , …, N,​K
​​ }. A continuous subsequence is defined to be { N​i, N,i+1, …,N​j} where 1≤i≤j≤K. 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
譯文
在k個數中,找最大子序列,最大子序列是連續子序列,其元素總和最大。例如,給定序列{-2,11,-4,13,-5,-2},其最大子序列是{11,-4,13},最大和為20。

現在你應該找到最大的總和,以及最大子序列的第一個和最後一個數字。

輸入規格:
每個輸入檔案包含一個測試用例。每個案例佔兩行。第一行包含正整數K(≤ 1 0 0 0 0)。第二行包含K數字,用空格分隔。

輸出規格:
對於每個測試用例,在一行中輸出最大總和,以及最大子序列的第一個和最後一個數字。數字必須用一個空格分隔,但在一行的末尾必須沒有多餘的空格。如果最大子序列不唯一,則輸出索引最小的子序列我和j(如樣本案例所示)。如果全部K數是負數,然後它的最大總和被定義為0,你應該輸出整個序列的第一個和最後一個數。

樣本輸入:
10
-10 1 2 3 4 -5 -23 3 7 -21
樣本輸出:
10 1 4

#include<cstdio>
using namespace std;
int data[10010];
int main()
{
	int n;
	scanf("%d", &n);
	int sum = 0;
	int start_index = 0;
	int end_index = n - 1;
	int start = 0;
	int max = -1;//初始值必須為負數,否則最大字序列和為零的時候,會有測試點過不了
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &data[i]);
		sum += data[i];
		if (sum < 0)
		{
			sum = 0;
			start = i + 1;
		}
		else if (sum > max)
		{
			max = sum;
			start_index = start;
			end_index = i;
		}
	}
	if (max < 0)max = 0;//當所有的元素都是負數的時候,應該將max賦值為0
	printf("%d", max);
	printf(" %d", data[start_index]);
	printf(" %d", data[end_index]);
	return 0;
}