求子数组的最大和

来源:互联网 发布:虚拟机linux共享文件夹 编辑:程序博客网 时间:2024/06/10 03:52

1.题目:求子数组的最大和

   输入一个整形数组,数组里有正数也有负数。

   数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

   求所有子数组的和的最大值。要求时间复杂度为O(n)。

   例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18

2. 解题思路

    当我们加上一个正数时,和会增加;当我们加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数

将会减少接下来的和

3. 代码实现

/////////////////////////////////////////////////////////////////////////////
// Find the greatest sum of all sub-arrays
// Return value: if the input is valid, return true, otherwise return false
/////////////////////////////////////////////////////////////////////////////
bool FindGreatestSumOfSubArray
(
      int *pData,          // an array
      unsignedint 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))
            returnfalse;

      int nCurSum = nGreatestSum = 0;
      for(unsignedint 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(unsignedint i = 1; i < nLength; ++i)
            {
                  if(pData[i] > nGreatestSum)
                        nGreatestSum = pData[i];
            }
      }

      returntrue;
}


原创粉丝点击