# PAT 甲级 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

$dp[i] = max\begin{Bmatrix} A[i],dp[i-1]+A[i] \end{Bmatrix}$

// 这题的目的是求出一个序列的子序列，使得子序列的和最大
// 用暴力破解无法承受复杂度，这需要动态规划的思路
#include <bits/stdc++.h>

using namespace std;

const int maxn = 10010;

int A[maxn],dp[maxn];    //A[i] 存放序列 dp[i]存放以A[i] 为结尾的连续序列的最大和
int left_r[maxn]={0};

int main()
{
int flag = 0;
int n,k=0;        //k代表右边界
int max_number = -1;
scanf("%d",&n);
for(int i = 0;i<n;i++)
{
scanf("%d",&A[i]);
}
dp[0] = A[0];
flag =(A[0]>=0)?1:0;  //如果出现大于0的数,flag就变为1
left_r[0] = 0;
for(int i = 1;i<n;i++)
{
if(A[i]>=0)
{
flag =1;
}
dp[i] = max(A[i],dp[i-1]+A[i]);
if(A[i]>dp[i-1]+A[i])
{
left_r[i] = i;
}
else
{
left_r[i] = left_r[i-1];
}
}
for(int j = 0;j<n;j++)
{
if(max_number<dp[j])
{
max_number = dp[j];
k = j;
}
}
if(flag==1)
{
printf("%d %d %d",dp[k],A[left_r[k]],A[k]);
}
else if(flag==0)
{
printf("0 %d %d",A[0],A[n-1]);
}
return 0;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

时间领主大锤

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

06-22 1050