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.
给定一个K个整数序列,一个连续的子列和定义是N11,N2,N3 下标小于k,最大的子列he是最大元素1之和,举个例子,给定一个序列{-2,111,-4,14,-5,-2},最大的子列和{11,-4,13}它的合是20.现在要求你找出1最大的合伙,从起始数字到结束数字
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.
输入规格:每个输入文件包含一个测试样例,每个样例1占据两行,第一行包含正整数K,第二行包含K个整数,每个一个空格。
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.
针对每个测试案例,输出一行最大的和,然后是起始的第一个数字和最后一个数字,两个数字必须有一个空格隔开,但是最后不能有空格,如果序列不唯一,输出最小的序列i与j,如果所有的数字都是负,那么定义最大子列和为负数,要求你输出整个序列。
核心思路
利用dp进行更新,dp采用从下标1到下标n结束
测试源码
#include<iostream>
using namespace std;
int main()
{
int K,a[10001],sum[10001],result=-1,head,tail;
cin >> K;
for(int i =1;i<=K;i++) cin >> a[i];
sum[0]= 0;
for(int i = 1;i<=K;i++) sum[i] = sum[i-1]+a[i];
int lowest = 0;
for(int end = 1;end<=K;end++){
if(sum[end]-sum[lowest]>result){
result = sum[end]-sum[lowest];
head = a[lowest+1];
tail = a[end];
}
if(sum[lowest]>sum[end]) lowest = end;
}
if(result<0) cout<< 0 << " " << a[1] << " " << a[K];
else cout << result << " " << head << " " << tail;
return 0;
}