中國大學MOOC-陳越、何欽銘-數據結構-2015秋 01-複雜度2 Maximum Subsequence Sum (25分)

01-複雜度2 Maximum Subsequence Sum   (25分)

Given a sequence of K integers { N1,N2, ..., NK }. A continuous subsequence is defined to be { Ni,Ni+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 integerK (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
  • 時間限制:200ms
  • 內存限制:64MB
  • 代碼長度限制:16kB
  • 判題程序:系統默認
  • 作者:陳越
  • 單位:浙江大學

大致題意:

此題爲 最大子列和 的變式,找出序列中的最大子序列之和,並輸出子序列中初始位的數和末位的數

解題思路:

用在線處理的方式,用thisMax儲存當前臨時序列和,如果大於最大maxSum的值,則更新maxSum的值

如果thisSum的值小於0時,將thisSum的值賦爲0,因爲thisSum小於0時,再加上一個數肯定比之前還要小

具體解答請看以下代碼:

#include <iostream>
 /*
  * author:Fayne
  * time:2015-9-2 21:24:16 
  *thisSum用於保存臨時序列之和,maxSum更新最大序列和
  *left, right分別表示最大序列的左右序號,tempLeft保存臨時左端的序號 
  */ 
using namespace std;
int A[10010];

int main()
{
	int k, i;
	cin >> k;
	for ( i=0; i<k; i++ )
		cin >> A[i];
	int left = 0, right = k-1, maxSum = -1, thisSum = 0, tempLeft;//maxSum賦初值爲-1爲了解決出現全部序列爲負的情況 
	for ( i=0; i<k; i++ )
	{
		thisSum += A[i];
	
		if ( thisSum > maxSum )//如果臨時序列和大於最大和,則更新最大和 
		{
			maxSum = thisSum;
			left = tempLeft;//將臨時左端的序號賦值給左端序號 
			right = i;
		}
		else if ( thisSum < 0 )//thisSum小於0時,從此刻下一個開始重新求和 
		{
			thisSum = 0;
			tempLeft = i+1;//把此刻的下一序號賦值給臨時左端序號 
		}
	}
	if ( maxSum < 0 )//maxSum < 0 說明整個序列全爲負數,根據題意,最大和應該爲0 
		maxSum = 0;
	cout << maxSum << " " << A[left]<< " " << A[right]<< endl;
	
	return 0;
}

注意題意:If all theK numbers are negative, then its maximum sum is defined to be 0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章