标签:blog http io ar os sp for div on
6 1 -2 3 5 -1 2 5 6 -1 5 4 -7
10 14
思路很好
设“最大和”对应的数组的最左边下标和最右边下标分别为 i,j. ( 0 <= i < j < n )
分两种情况:
1. 当子数组“不跨越”母数组的时候:
用常规求最大子串和的方法,求出一个最优值。
2. 当子数组“跨越”母数组的时候:
要求该“跨越子数组”的最大子串和,则需在母数组中寻找一个“不跨越”的最小子串和,然后用总和减去该
值,即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<vector>
using namespace std;
const int maxn=100005;
int n,f[maxn],sum;
void dp()
{
int t1,t2;
t1=f[0],t2=f[0];
int Min,Max;
Max=t1,Min=t2;
for(int i=1;i<n;i++)
{
if(t1<=0)
t1=f[i];
else
t1+=f[i];
if(t2>=0)
t2=f[i];
else
t2+=f[i];
Max=max(Max,t1) ;
Min=min(Min,t2) ;
}
Max=max(Max,sum-Min);
printf("%d\n",max(Max,0));
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
sum=0;
for(int i=0;i<n;i++)
scanf("%d",&f[i]),sum+=f[i];
dp();
}
return 0;
}
标签:blog http io ar os sp for div on
原文地址:http://www.cnblogs.com/a972290869/p/4099975.html