题目描述
原题链接:1007 Maximum Subsequence Sum
解题思路
读题,给出一个数组N,求这个数组的一个子序列,使得这个子序列的和最大
——很明显的动态规划问题
建立动态规划数组dp,其中dp[i]表示以元素N[i]结尾的子序列的最大和,则dp[i]=max(dp[i-1]+N[i], N[i])
同时,为了满足输出,在动态规划的同时还需要建立数组index记录子序列的开始元素下标,index[i]表示以N[i]结尾的最大和子序列的开始元素下标,做如下处理:
对于dp[i]而言,如果dp[i-1]>0,则index[i]=index[i-1], dp[i]=dp[i-1]+N[i]
否则index[i]=i, dp[i]=N[i]
注意还有特殊情况: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). 【如果有多个最大值序列,则输出i和j最小的】
PS:为了节省空间,本题采用滚动数组的方式
AC代码
#include <bits/stdc++.h>
using namespace std;
const int len = 1e5+1;
int N[len];
int main () {
int k, dp=0, index=0; scanf("%d", &k);
int ans=-1, ans_begin, ans_end;
for (int i=0;i<k;i++) {
scanf("%d", &N[i]);
if (dp > 0) dp+=N[i];
else {
dp=N[i];
index = i;
}
if (dp > ans) {
ans=dp;
ans_begin=index;
ans_end=i;
}
}
if (ans >= 0) printf("%d %d %d\n", ans, N[ans_begin], N[ans_end]);
else printf("0 %d %d\n", N[0], N[k-1]);
return 0;
}