1.分治法 O(nlogn)
//分治法
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int maxn=50000+5;
int a[maxn];
LL max_sub(int left,int right)
{
if(left==right) return a[left]>0?a[left]:0;
int mid=(left+right)/2;
LL sum,left_sum,right_sum;
left_sum=max_sub(left,mid);
right_sum=max_sub(mid+1,right);
sum=0;
LL left_max=0,right_max=0;
for(int i=mid;i>=left;i--)
{
sum+=a[i];
if(sum>left_max) left_max=sum;
}
sum=0;
for(int i=mid+1;i<=right;i++)
{
sum+=a[i];
if(sum>right_max) right_max=sum;
}
return max(left_sum,max(right_sum,left_max+right_max));
}
int main()
{
int n;
while(scanf("%d",&n)==1&&n)
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
cout<<max_sub(0,n-1)<<endl; //左闭右闭的区间
}
return 0;
}
2.dp O(n)
//dp
#include <iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int maxn=50000+5;
int a[maxn];
int main()
{
int n;
while(scanf("%d",&n)==1&&n)
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
LL m=0,cnt=0;
for(int i=1;i<=n;i++)
{
if(m+a[i]<a[i]) m=a[i];
else m+=a[i];
if(m>cnt) cnt=m;
}
cout<<cnt<<endl;
}
return 0;
}