/*auther:hansongjiang*/
#include<iostream>
#include<vector>
using namespace std;
//http://www.cnblogs.com/CCBB/archive/2009/04/25/1443455.html
//四种方法,一个一个写
//第一个O(N*N) */从第i开始累加的最大的值
int getMax0(int a[],int len)
{
int maxSum=0;
for(int i=0;i<len;i++)
{
int thisSum=0;
for(int j=i;j<len;j++)
{
thisSum+=a[j];
if(thisSum>maxSum)
{
maxSum=thisSum;
}
}
}
return maxSum;
}
//递归算法思路,就是分而治之,如何分,最简单的二分思路,下回写个二分查找。
int getMax1(int a[],int low,int high)
{
if(low==high)
{
if(a[low>0])
{
return a[low];
}
else
{
return 0;
}
}
int mid=(high+low)/2;
//左边low到mid的最大值
int left=getMax1(a,low,mid);
int right=getMax1(a,mid+1,high);
//求左右包括a[mid]的最大值和
int maxSumleft=0;
int thisSumleft=0;
int j=mid;
while(j>=low)
{
thisSumleft+=a[j];
if(maxSumleft<thisSumleft)
maxSumleft=thisSumleft;
j--;
}
j=mid+1;
thisSumleft=maxSumleft;
while(j<=high)
{
thisSumleft+=a[j];
if(thisSumleft>maxSumleft)
{
maxSumleft=thisSumleft;
}
j++;
}
return maxSumleft;
}
//o(n)
int getMax2(int a[],int len)
{
int sum=0;
int tempSum=0;
for(int i=0;i<len;i++)
{
tempSum+=a[i];
if(tempSum<0)
tempSum=0;
if(tempSum>sum)
{
sum=tempSum;
}
}
return sum;
}
void main()
{
int a[]={3,5,6,-9,1};
int sum=getMax0(a,5);
cout<<sum<<endl;
sum=getMax2(a,5);
cout<<"效率最高的结果"<<sum<<endl;
sum=getMax1(a,0,4);
cout<<"nlogn"<<sum;
}
数组中连续最大和实现
最新推荐文章于 2023-06-08 00:15:24 发布