题意:略
解析:动态规划,dp[i]代表以a[i]结尾的子段的最大和,最后找出最大值即可。
动态规划的思想就是利用之前的状态推出之后的状态,状态具有无后效性。
对这个题来说,分为两步,每一步就是一个状态的转移方式:
每一个状态dp[i] 都是从两步中选取最优的一个,一步是延续上一个子段,另一个是新起一个子段,不用考虑后续的状态,只需要注意这个状态的两步。
一个例子:
反思:1.注意数据范围最大5000*10^9,需要用long long。 2.不开dp数组也可以,实际上整个过程只用到了当前状态和前一个状态,所以也可以用两个变量替代dp数组。
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <iomanip>
#include <bitset>
using namespace std;
#define eps (1e-6)
#define LL long long
#define pi acos(-1.0)
#define ALL(a) (a.begin(),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define IOS cin.tie(0) , cout.sync_with_stdio(0)
#define PRINT(a,b) cout << "#" << (a) << " " << (b) << endl
#define DEBUG(a,b) cout << "$" << (a) << " " << (b) << endl
#define line cout << "\n--------------------\n"
const LL INF = 1e18+100;
const int MAXN = 5e4 + 5;
const int MOD = 1e9+7;
int n;
LL a[MAXN]; //数据范围5000*10^9炸int
LL dp[MAXN]; //表示以a[i]结尾产生的最大子段和
void CONFIRM()
{
for(int i=0; i<n; ++i)
PRINT(i, dp[i]);
line;
}
void SOLVE()
{
ZERO(dp);
dp[0] = max((LL)0, a[0]);
for(int i=1; i<n; ++i){
if(dp[i-1] < 0){
dp[i] = max(a[i] , (LL)0); //如果上一个<0,舍弃之
}
else{
dp[i] = a[i] + dp[i-1]; //上一个>=0,加上a[i]表示以i结尾的最大子段和
}
}
//CONFIRM();
LL ans = 0;
for(int i=0; i<n; ++i)
ans = max(dp[i],ans); //找出最大值
cout << ans;
return;
}
int main()
{
IOS;
cin >> n;
for(int i=0 ;i<n; ++i)
cin >> a[i];
SOLVE();
return 0;
}
不开数组的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <iomanip>
#include <bitset>
using namespace std;
#define IOS cin.tie(0) , cout.sync_with_stdio(0)
int n;
LL sum = 0;
void SOLVE()
{
LL num;
LL sum, maxsum;
num = sum = maxsum = 0;
while(n--){
cin >> num;
sum = max(sum, (LL)0) + num;
maxsum = max(sum, maxsum);
}
cout << maxsum;
return ;
}
int main()
{
IOS;
cin >> n;
SOLVE();
return 0;
}