数组中连续最大和实现

/*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;
 
 
 
 
 
 
 }











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值