题目链接
首先这是一道动态规划,动态规划
然后就是选与不选的问题
如果选就是dp[i] =dp[i-1]+num[i];
如果不选是 dp[i] = num[i];
pre数组用于记录开始的位置
如果选pre[i] = pre[i - 1];
这样他就一直保持着开始选的那个位置
如果不选pre[i] = i;
然后就完成啦,dp保存的是到i的位置的最大的值
当然这里还需要注意这一句
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.
这里当然就是说如果所有的数都是复数然后就这样输出就可以了
if (Maxvalue == -1) {
cout << "0" << " " <<num[0]<< " "<<num[n-1];
}
#include<iostream>
#include<algorithm>
using namespace std;
int dp[10100];
int num[10100];
int pre[10100];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num[i];
}
dp[0] = num[0];
pre[0] = 0;
for (int i = 1; i < n; i++) {
if (num[i] > dp[i - 1] + num[i]) {
dp[i] = num[i];
pre[i] = i;
}
else {
dp[i] =dp[i-1]+num[i];
pre[i] = pre[i - 1];
}
}
int Maxindex, Maxvalue = -1;
for (int i = 0; i < n; i++) {
if (dp[i] > Maxvalue) {
Maxvalue = dp[i];
Maxindex = i;
}
}
if (Maxvalue == -1) {
cout << "0" << " " <<num[0]<< " "<<num[n-1];
}
else {
cout << Maxvalue << " " << num[pre[Maxindex]] << " " << num[Maxindex];
}
return 0;
}