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

来源:互联网 发布:win32 api 知乎 编辑:程序博客网 时间:2024/05/16 19:31

问题描述:一个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 0
原创粉丝点击