剑指offer面试题31:连续子数组的最大和

解决面试题31,寻找一个N个整数元素数组的连续子数组,使得子数组之和最大。通过从数组尾部开始遍历,使用两个变量nStart和nAll更新最大子数组值。若子数组累计值小于等于0,则舍弃并从当前元素重新计算;否则,累加当前元素。最终得到最大子数组和。
摘要由CSDN通过智能技术生成

问题描述:一个N个整数元素的一维数组(A[0],A[1],...,A[n-2],A[n-1]),这个数组当然有很多子数组,那么子数组之和的最大值是多少呢?

解题思路:定义两个变量,nStart表示以当前元素为首的子数组的最大值,nAll表示遍历到当前元素时最大子数组的值.从数组的尾元素开始遍历.有如下的递推公式:

nStart = max(A[i], nStart + A[i]);

nAll = max(nStart, nAll);

算法伪代码实现如下:

int max(int x, int y)
  {
          return ((x > y) ? x : y);
  }
  
 int MaxSum(int* A, int n)
  {
          nStart = A[n-1];
           nAll = A[n-1];
          for (i = n-2; i >=0; i--)
          {
                  nStart = max(A[i], nStart + A[i]);
                  nAll = max(nStart, nAll);
          }
          return nAll;
  }
上述解题思路是一种通用的实现方式,剑指offer种给出了另一种方法,不过有个前提条件就是: 要处理的数组中既有正数又有负数.

这种情况下的解题思路为:定义两个变量,nCurSum表示当前连续子数组的最大值,nGreateSum表示遍历到当前元素时最大子数组的值.解题思路如下:

从数组开头开始遍历,每遍历一个元素之前首先查看nCurSum的正负号,如果小于或等于0,则说明之前累加的元素加上当前的元素值,肯定要小于当前的元素值,那么丢弃原来的累计值(这与数组元素的特性有关),将nCurSum的值至为当前元素值.

如果nCurSum值大于0,则令:nCurSum += pData[i].

每次处理完一个元素都要将nCurSum值与之前的nGreateSum值比较,并实时更新nGreateSum的值.

bool FindGreatestSumOfSubArray
(
      int *pData,           // an array
      unsigned int nLength, // the length of array
      int &nGreatestSum     // the greatest sum of all sub-arrays
)
{
      // if the input is invalid, return false
      if((pData == NULL) || (nLength == 0))
            return false;

      int nCurSum = nGreatestSum = 0;
      for(unsigned int i = 0; i < nLength; ++i)
      {
            nCurSum += pData[i];

            // if the current sum is negative, discard it
            if(nCurSum < 0)
                  nCurSum = 0;

            // if a greater sum is found, update the greatest sum
            if(nCurSum > nGreatestSum)
                  nGreatestSum = nCurSum;

      }

 
      // if all data are negative, find the greatest element in the array
      if(nGreatestSum == 0)
      {
            nGreatestSum = pData[0];
            for(unsigned int i = 1; i < nLength; ++i)
            {
                  if(pData[i] > nGreatestSum)
                        nGreatestSum = pData[i];
            }
      }

      return true;
} 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值