数组中最大和的子序列

 

数组中,一部分整数,一部分复数;当然可能全是复数。

求出这个数值中能够得到最大和的子序列。

 

原理:用动态规划方法。一个临时变量记录从上一次负数开始的临时最大值的序列,如果它比上一个temp值大的话,就用它替代上一个成为最大的子值。

注意:最后有一步骤检查,看是否全部的数据都是负数,如果是的话,重新搜索一遍数组找到最小的负数,作为最大子序列的值。

  1. bool FindGreatestSumOfSubArray(
  2.  int *pData,           // an array
  3.  unsigned int nLength, // the length of array
  4.  int &nGreatestSum     // the greatest sum of all sub-arrays
  5.  ){
  6.     // if the input is invalid, return false
  7.     if((pData == NULL) || (nLength == 0))
  8.         return false;
  9.     int nCurSum = nGreatestSum = 0;
  10.     for(unsigned int i = 0; i < nLength; ++i){
  11.         nCurSum += pData[i];
  12.         // if the current sum is negative, discard it
  13.         if(nCurSum < 0)
  14.             nCurSum = 0;
  15.         
  16.         // if a greater sum is found, update the greatest sum
  17.         if(nCurSum > nGreatestSum)
  18.             nGreatestSum = nCurSum;
  19.     }
  20.     // if all data are negative, find the greatest element in the array
  21.     if(nGreatestSum == 0){
  22.         nGreatestSum = pData[0];
  23.         for(unsigned int i = 1; i < nLength; ++i){
  24.             if(pData[i] > nGreatestSum)
  25.                 nGreatestSum = pData[i];
  26.         }
  27.     }
  28.     return true;
  29. int main(int argc, char* argv[]){
  30.     int arr[] = {1,8,3,-6,9,4,-10,12,99};
  31.     int result = 0;
  32.     if ( FindGreatestSumOfSubArray( arr, sizeof(arr)/sizeof(int), result ))
  33.         printf( "Hello World:%d", result);
  34.     else
  35.         printf( "Bad Hello World:%d", result);
  36.     return 0;
  37. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值