连续子序列的最大和

分析: 每次都对前i-1项的最大和sum进行判断,如果sum < 0;

则a[i] 肯定大于a[i] + sum的和,这时执行 sum = a[i],否则执行sum += a[i];

但是这时还并不知道max和sum谁更大,故执行

max = max > sum ? max : sum;

#include <bits/stdc++.h>
using namespace std;

int maxSum( vector<int>&b,int n);
int main()
{
  int tmp;
  vector<int> a;
  char ch;
  while (cin >> tmp)
  {
          a.push_back(tmp);
          if ((ch = getchar())== '\n')//遇到enter就结束
                  break;
  } //以上是为了给数组赋值
int max = maxSum(a,a.size());
  cout << max;
  return 0;
}

int maxSum( vector<int>&b,int n)
{
  int max = b[0];
  int tmpMax = b[0];
   for(int i = 0; i < n; i++)
    {
      if(tmpMax > 0)
        tmpMax += b[i];  //如果前(i)项的和为正数,则加上
      else
        tmpMax = b[i];
      //到现在为止并不知道前 (i)项的和与前i项的和那个大
      max = max > tmpMax ? max : tmpMax;

    }
   return max;
}

另一个更精简的代码

int MaxSubsequenceSum( const int A[ ], int N )
{
    int ThisSum, MaxSum;
    ThisSum = MaxSum = A[0];
    for(int j = 1; j < N; j++ )
    {
        ThisSum = (ThisSum+A[j]) > A[j] ? (ThisSum+A[j]) :A[j]; 
        MaxSum = MaxSum > ThisSum ? MaxSum : ThisSum;
    }
    return MaxSum;
}

猜你喜欢

转载自blog.csdn.net/feixi7358/article/details/79754232