一、分治法:
算法复杂度:O(nlgn)
#include <iostream>
#include <vector>
using namespace std;
int A[]={-2,1,-3,4,-1,2,1,-5,4};
int CrossSubArray(int A[],int low,int high,int mid)
{
int left_max=0x80000000;
int right_max=0x80000000;
int sum=0;
for(int i=mid;i>=low;--i)
{
sum+=A[i];
if(sum>left_max) left_max=sum;
}
sum=0;
for(int i=mid+1;i<=high;++i)
{
sum+=A[i];
if(sum>right_max) right_max=sum;
}
return left_max+right_max;
}
int MaxSubArray(int A[],int low,int high)
{
if(low==high) return A[low];
int mid=(low+high)/2,L,R,Cr;
L=MaxSubArray(A,low,mid);
R=MaxSubArray(A,mid+1,high);
Cr=CrossSubArray(A,low,high,mid);
return max(max(L,R),Cr);
}
int main()
{
int n=sizeof(A)/sizeof(int);
cout<<MaxSubArray(A,0,n-1);
return 0;
}
二、Dp法:
算法复杂度:O(n)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v={-1,2,-5,3,5,9,-1,22,8};
int MaxSubArray(vector<int> v)
{
int maxsum=v[0],sum=0;
for(auto x:v)
{
sum+=x;
maxsum=max(maxsum,sum);
sum=max(sum,0);
}
return maxsum;
}
int main()
{
cout<<MaxSubArray(v);
return 0;
}