甲级PAT 1007 Maximum Subsequence Sum(给出部分坑的测试情况)

1007 Maximum Subsequence Sum (25)(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

 题目要求:

给出一个序列(可能包含负数、正数和0),找出这个序列中最大连续子序列和,输出这个最大值,以及子序列的第一个数和最后一个数。

若序列中的所有数都是负数,则最大的子序列和为0,并输出整个序列的第一个数和最后一个数。

解题思路:

这题肯定是一个动态规划的题目。首先要找到状态方程式,用dp[i]表示序列a中第i个数a[i]对应的最大连续子序列和,从下标0开始依次更新后面的dp[i]。初始值dp[0]=a[0]。从下标1开始,dp[i]只有两种情况,dp[i]=a[i] (dp[i-1]+a[i] <= a[i])  或者dp[i]=dp[i-1]+a[i] (dp[i-1]+a[i] >a[i])。然后用start[i]来存储序列每个数局部最大连续子序列的起始下标。用sum来存储当前所找到最大连续子序列的和,用l表示所找到最大连续子序列的第一个数下标,用r表示最大连续子序列的最后一个数下标。记得设初始值,start[0] = 0,sum=a[0],l=0,r=0。每次dp[i]>sum时更新sum,l,r的值。

完整代码:

#include<iostream>
using namespace std;
#define maxsize 10001

int a[maxsize];
int dp[maxsize];
int start[maxsize];

int main(){
	int K,i,l,r,sum,b;
	cin>>K;
	for(i=0;i<K;i++){
		cin>>a[i];
	}
	dp[0] = a[0];
	sum = a[0];
	start[0] = 0;
	l = 0;
	r = 0;
	for(i=1;i<K;i++){
		if(dp[i-1]+a[i]>a[i]){
			dp[i] = dp[i-1]+a[i];
			start[i] = start[i-1];
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}else if(dp[i-1]+a[i]==a[i]){
			start[i] = start[i-1];
			dp[i] = a[i];
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}else{
			dp[i] = a[i];
			start[i] = i;
			if(dp[i]>sum){
				sum = dp[i];
				l = start[i];
				r = i;
			}
		}
	}
	if(sum >= 0){
		cout<<sum<<" "<<a[l]<<" "<<a[r];
	}else{
		cout<<0<<" "<<a[0]<<" "<<a[K-1];
	}
	
	return 0;
} 

 坑的测试情况(之前自己写代码不通过的例子):

1.

5

-9 9 -9 -9 9

2.

5

9 -9 -9 -9 9

3.

5

0 9 -9 0 9

4.

1

-5

 

 

点赞