您的位置:首页 > 产品设计 > UI/UE

1007. Maximum Subsequence Sum (25)

2015-11-04 12:29 351 查看
1.注意判断全为负数的情况,第一个数是否为负数,不要漏判断

2.实际上采用动态规划,dp[i]=max{dp[i-1]+num[i],num[i]},dp[i]一定会包含当前的数字num[i],但是可以简化为判断dp[i-1]是否为负数

//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
//#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
using namespace std;
int main(void) {

int n;
cin >> n;
if (n == 0)
{
cout << "0 0 0" << endl;
return 0;
}
long long *num = new long long
;
for (int i = 0; i < n; i++)
{
cin >> num[i];
}
vector<pair<int, long long>> dp(n, { 0, 0 });
dp[0].first = 0;
dp[0].second = num[0];
bool negative = true;
if (num[0] >= 0) negative = false;//注意第一个数也要判断正负
for (int i = 1; i < n; i++)
{
if (negative&&num[i] >= 0) negative = false;//判断是否全负数
if (dp[i - 1].second <= 0)
{
dp[i].first = i;
dp[i].second = num[i];
}
else
{
dp[i].first = dp[i - 1].first;
dp[i].second = dp[i - 1].second + num[i];
}

}

if (negative)
{
cout << 0 << " " << num[0] << " " << num[n - 1] << endl;
}
else
{
long long maxAns = -1; int index = -1;
for (int i = 0; i < n; i++)
{
if (maxAns < dp[i].second)
{
maxAns = dp[i].second;
index = i;
}
}
cout << dp[index].second << " " << num[dp[index].first] << " " << num[index] << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: