码迷,mamicode.com
首页 > 其他好文 > 详细

Maxmum subsequence sum problem

时间:2016-10-24 23:15:06      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:first   ati   ddl   sum   different   ref   possibly   diff   prefix   

We have a lot of ways to solve the maximum subsequence sum problem, but different ways take different time.

1、Brute-force algorithm

int maxSubSum1(const vector<int> &a)
{
	int maxSum=0;
	
	for(int i=0;i<a.size();i++)
		for(int j=i;j<a.size();j++)
		{
			int sum=0;
			for(int k=i;k<=j;k++)
				sum+=a[k];
			
			if(sum>maxSum)
				maxSum=sum;
		}
		
		return maxSum;
}
/*The running time is O(n^3)
It takes too much time.
*/

2、a little imporvement

int maxSubSum2(const vector<int>& a )
{
    int maxSum=0;
   
     for(int i=0;i<a.size();i++)
     {
          int sum=0;
     
          for(int j=i;j<a.size();j++)
          {
                sum+=a[j];
                if(maxSum<sum)
                {
                     maxSum=sum;
                }
          }
     }

     return maxSum;
}

3. Divide-conquer algorithm

We can divide this problem into three parts:
(1) First half;

(2) cross the middle parts;

(3) second part;

What we need to do is to find the max sum of the three part.

 

int max3(int a, int b, int c)
{
	if(a>b)
	{
		if(a>c)return a;
		else return c;
	}
	else
	{
		if(c>b)return c;
		else return b;
	}
}

int maxSubSum3(cosnt vector<int >& a, int left, int right)
{
     if(left==right)
        if(a[left]>0) return a[left];
        else return 0;

     int center= (left+right)/2;
     int maxLeftSum=maxSumRec(a, left, center);
     int maxRightSum=maxSumRec(a, center+1, right);
   
     int maxLeftBoderSum=0, leftBoderSum=0;
	for(int i=center;i>=left;i--)
	{
		leftBoderSum+=a[i];
		if(leftBoderSum>maxLeftBoderSum)
			maxLeftBoderSum=leftBoderSum;
	}
	
	int maxRightBoderSum=0, leftBoderSum=0;
	for(int i=center+1;i<=right;i++)
	{
		rightBoderSum+=a[i];
		if(rightBoderSum>maxRightBoderSum)
			maxRightBoderSum=rightBoderSum;
	}
	
	return max3(maxLeftSum, maxLeftBoderSum+maxRightBoderSum,maxRightSum);
}

4. The best algorithm

If the start is negative, the sum of the subsequence can not be the max. Hence, any negative subsequence cannot possibly be a prefix of the optimal subsequence.

int maxSubSum4(const vector<int> & a)
{
	int maxSum=0, sum=0;
	
	for(int i=0;i<a.size();i++)
	{
		sum+=a[i];
		
		if(sum>maxSum)
			maxSum=sum;
		else if(sum<0)
			sum=0;
	}
	
	return maxSum;
}

  

Maxmum subsequence sum problem

标签:first   ati   ddl   sum   different   ref   possibly   diff   prefix   

原文地址:http://www.cnblogs.com/KennyRom/p/5994914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!