首页 > 代码库 > Maxmum subsequence sum problem

Maxmum subsequence sum problem

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