1007. 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 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 -21Sample Output:
10 1 4
题意:
给你一串数字,求和最大的子串。
题解:
简单动规,状态转移方程为:
if(sum[i - 1] < 0){//如果之前的串和为负数,那么不如不要
sum[i] = v[i];
st[i] = i;
}
else{//否则就留下,因为题目要求和相等时取开头位置最前的,所以等于0也留下
sum[i] = sum[i - 1] + v[i];
st[i] = st[i-1];
}
在计算sum[i]和st[i]的过程中即可同时记录最大和。
考点:
简单动规
坑点:
无
#include <iostream>
using namespace std;
int main()
{
int n, i;
int max_, a, b;
int v[10000];
int sum[10000];
int st[10000];
cin >> n;
for(i = 0; i < n; i++)
cin >> v[i];
sum[0] = v[0];
st[0] = 0;
max_ = v[0];
for(i = 1; i < n; i++){
if(sum[i - 1] < 0){
sum[i] = v[i];
st[i] = i;
}
else{
sum[i] = sum[i - 1] + v[i];
st[i] = st[i-1];
}
if(sum[i] > max_){
max_ = sum[i];
a = st[i];
b = i;
}
}
if(max_ < 0) cout << "0 " << v[0] << " " << v[n - 1] << endl;
else cout << max_ << " " << v[a] << " " << v[b] << endl;
//system("pause");
}