题目描述:
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } 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 Knumbers, 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 nums[0] nums[K - 1].
设dp[i]是以nums[i]为结尾的连续递增子序列的最大和,L[i]则是该子序列的长度。输出最后的dp[i]的最大值以及首尾元素。
#include<bits/stdc++.h>
using namespace std;
int dp[10001];
int nums[10001];
int L[10001];
int main()
{
int K;
scanf("%d", &K);
int z_count = 0;
for(int i = 0; i < K; i++)
{
scanf("%d", &nums[i]);
if(nums[i] < 0)
z_count++;
}
if(z_count == K)
{
printf("0 %d %d\n", nums[0], nums[K - 1]);
return 0;
}
dp[0] = nums[0];
L[0] = 1;
for(int i = 1; i < K; i++)
{
if(dp[i - 1] + nums[i] > nums[i])
{
L[i] = L[i - 1] + 1;
dp[i] = dp[i - 1] + nums[i];
}
else
{
L[i] = 1;
dp[i] = nums[i];
}
}
int tmax = -1;
int index = 0;
for(int k = 0; k < K; k++)
{
if(dp[k] > tmax)
{
index = k;
tmax = dp[k];
}
}
printf("%d %d %d\n", dp[index], nums[index - L[index] + 1],nums[index]);
return 0;
}