#include <iostream>
#include<algorithm>
using namespace std;
class BiggestArray{
public:
//蛮力枚举法,时间复杂度O(n3),空间复杂度O(1)
int FindTheBiggestMethod1(int*a,int n)
{
int maxSum=INT_MIN;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
int sum=0;
for(int k=i;k<=j;k++)
{
sum+=a[k];
}
if(maxSum<sum) maxSum=sum;
}
}
return maxSum;
}
//优化枚举法,时间复杂度O(n2),空间复杂度O(n2)
int FindTheBiggestMethod2(int*a,int n)
{
int auxiliaryMetrix[n][n];
int maxSum=INT_MIN;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(i==j) auxiliaryMetrix[i][j]=a[i];
else auxiliaryMetrix[i][j]=auxiliaryMetrix[i][j-1]+a[j];
if(maxSum<auxiliaryMetrix[i][j]) maxSum=auxiliaryMetrix[i][j];
}
}
return maxSum;
}
//优化枚举法2,时间富足度O(n2),空间复杂度O(1)
int FindTheBiggestMethod3(int*a,int n)
{
int lastSum;
int maxSum=INT_MIN;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(i==j)lastSum=a[i];
else lastSum+=a[j];
if(maxSum<lastSum) maxSum=lastSum;
}
}
return maxSum;
}
//分而治之,时间复杂度O(n*Log n)
int FindTheBiggestMethod4(int*a,int low,int high)
{
if(low==high) return a[low];
int mid=(low+high)/2;
int s1,s2,s3;
s1=FindTheBiggestMethod4(a,low,mid);
s2=FindTheBiggestMethod4(a,mid+1,high);
s3=CrossingSubArray(a,low,mid,high);
return max(max(s1,s2),max(s2,s3));
}
private:
int CrossingSubArray(int *x,int low,int mid,int high)
{
int SumLeft=INT_MIN,SumRight=INT_MIN;
int sum=0;
for(int i=mid;i>=low;i--)
{
sum+=x[i];
if(sum>SumLeft) SumLeft=sum;
}
sum=0;
for(int i=mid+1;i<=high;i++)
{
sum+=x[i];
if(sum>SumRight) SumRight=sum;
}
return SumRight+SumLeft;
}
};
void answer(int*a,int len,int choose)
{
BiggestArray ba;
if(choose==1)
cout<<ba.FindTheBiggestMethod1(a,len)<<endl;
if(choose==2)
cout<<ba.FindTheBiggestMethod2(a,len)<<endl;
if(choose==3)
cout<<ba.FindTheBiggestMethod3(a,len)<<endl;
if(choose==4)
cout<<ba.FindTheBiggestMethod4(a,0,len-1)<<endl;
}
int main()
{
int a[]={-1,-3,3,5,-4,3,2,-2,3,6};
int b[]={1,-2,4,5,-2,8,3,-2,6,3,7,-1};
int lenA=sizeof(a)/sizeof(a[0]);
int lenB=sizeof(b)/sizeof(b[0]);
cout<<"方法一:"<<endl;
cout<<"数组A的最大组数组是";
answer(a,lenA,1);
cout<<"数组B的最大子数组是";
answer(b,lenB,1);
//
cout<<endl<<endl;
cout<<"方法二:"<<endl;
cout<<"数组A的最大组数组是";
answer(a,lenA,2);
cout<<"数组B的最大子数组是";
answer(b,lenB,2);
cout<<endl<<endl;
cout<<"方法三:"<<endl;
cout<<"数组A的最大组数组是";
answer(a,lenA,3);
cout<<"数组B的最大子数组是";
answer(b,lenB,3);
cout<<endl<<endl;
cout<<"方法四:"<<endl;
cout<<"数组A的最大组数组是";
answer(a,lenA,4);
cout<<"数组B的最大子数组是";
answer(b,lenB,4);
cout<<endl<<endl;
cout<<"方法五:动态规划(最优解法)待续"<<endl;
return 0;
}