1.Time complexity O(n)
Analysis:traverse through the array ,and calculate the sum .if the sum of the first several number is less than 0,we could let the sum=a[i];(because the
the max sum subarray won't include the left elements.),if the sum is greater than 0.we add the current elements.Next if sum is greater than Maxsum,just let the Maxsum=sum.
int maxSum(int* a, int n)
{
int sum=a[0],MAXSUM=a[0];
int i=0,j=0;
for(i=0;i<n;i++)
{
if(sum+a[i]>=0)
sum=sum+a[i];
else sum=0;
if(sum>MAXSUM)MAXSUM=sum;
}
return MAXSUM;
}
2.Using divide and conquer; -O(nlogn)
The area of the subarray will only locate in three places.
a.all in the left sides
b.all in the right sides
c.in the center,some in the left or some in the right.
compare the three maxsum,then output the Maxsum.So use recursion we can divide the whole array until only one elements.
code:
int Max3(int a,int b,int c)
{
int Max = a;
if(b > Max)
Max = b;
if(c > Max)
Max = c;
return Max;
}
int Maxsum(int *a,int left,int right)
{
if(left==right)
if(a[left]>0)
return a[left];
else return a[left];
int center=(left+right)/2;
int Maxleft=0,Maxright=0,Maxcenter=0;
int leftsum=0,Maxleftcenter=a[center],Maxrightcenter=a[center+1];//middle sum
int i;
for( i=center;i>=left;i--)
{
leftsum=leftsum+a[i];
if(leftsum>Maxleftcenter)Maxleftcenter=leftsum;
}
int rightsum=0;
for( i=center+1;i<=right;i++)
{
rightsum=rightsum+a[i];
if(rightsum>Maxrightcenter)Maxrightcenter=rightsum;
}
Maxcenter=Maxleftcenter+Maxrightcenter;
Maxleft=Maxsum(a,left,center);//left sum<span style="white-space:pre"> </span>
Maxright=Maxsum(a,center+1,right);//right sum
return Max3(Maxcenter,Maxleft,Maxright);
}
int Maxsum(int* a,int length)
{
int sum[100];
sum[0]=a[0];
int result=a[0];
for(int i=0;i<length-1;i++)
{
if(a[i+1]>sum[i]+a[i+1])
sum[i+1]=a[i+1];
else sum[i+1]=sum[i]+a[i+1];
if(result<sum[i])result=sum[i];
}
return result;
}
int main()
{
//int a[]={1, -2, 3, 10, -4, 7, 2, -5};
int a[]={-6,-2,-1,-4}; //测试全是负数的用例
cout<<Maxsum(a,0,3)<<endl;
return 0;
}
3.DP Alogrithm
Let sum[i] represent the subarray which include array[i] and have greatest sum.result is the currently greatest sum .For the array[i+1] :
a.it might be a new subarray;
b.it will add to the current subarray.
sum[i]=max(sum[i]+a[i+1],a[i+1]);
result=max(result,sum[i+1]);
code:
int Maxsum(int* a,int length)
{
int sum[100];
sum[0]=a[0];
int result=a[0];
for(int i=0;i<length-1;i++)
{
if(a[i+1]>sum[i]+a[i+1])
sum[i+1]=a[i+1];
else sum[i+1]=sum[i]+a[i+1];
if(result<sum[i])result=sum[i];
}
return result;
}