动态规划法求最大子序列和

算法一:直观法,时间复杂度O(n^3)

#include
#include
using namespace std;
int maxsubsequencesum(const int a[], int n)
{
    int thissum, maxsum, k;
   
    maxsum = 0;
    for(int i =0; i            for(int j= i;j            {
            thissum = 0;
            for(int k=i;k<=j;k++)//所有子序列和
            thissum += a[k];
           
            if(thissum > maxsum )
            maxsum = thissum;
            }
            return maxsum;
}
int main()
{
    int *p;
    int n;
   
    while(cin>>n){
        p= new int[n];
        for(int i = 0;i < n;i++)
            cin>>p[i];
        cout<< maxsubsequencesum(p,n);
    }
    delete[] p;
   
    return 0;
}

http://www.programfan.com/blog/article.asp?id=28152
动态规划的算法 maxSubSequenceSum3  O(n)

/*
 * 动态规划实现,算法复杂度O(n)
 */
int maxSubSequenceSum3(int a[], int len)
{
    int i;
    int curSum; /* 当前序列和 */
    int maxSum; /* 最大序列和 */

    /* 初始化当前序列和为0 */
    curSum = 0;

    /* 初始化最大子序列和为序列第一个元素 */
    maxSum = a[0];

    /* 开始循环求子序列和 */
    for (i = 0; i < len; i++)
    {
        curSum = curSum + a[i];

        /* 与最大子序列和比较,更新最大子序列和 */
        if (curSum > maxSum)
        {
            maxSum = curSum;
        }

        /* 动态规划部分,舍弃当前和为负的子序列 */
        if (curSum < 0)
        {
            curSum = 0;
        }
    }
    return maxSum;
}

 

 记录下标:

 

#include
int  j=1,k=0;
int maxsum(int p[],int n)
{
 int i,currsum=0;
 int maxsum=p[0];
 for (i=0;i {
  currsum=currsum+p[i];
  if(currsum>maxsum) {maxsum=currsum;k=i+1;}
  if(currsum<0) {currsum=0;n=j+1;}
 
 }
 
return maxsum;

}

 

int main()
{
 int n,i;
 int a[1000];

 scanf("%d",&n);

  for(i=0;i  {
  scanf("%d",&a[i]);

  }
   //maxsum=maxsum(a,n);

 printf("%d/n",maxsum(a,n));
 printf("%d,%d/n",j,k);
return 0;
}

 

你可能感兴趣的:(acm)