ciano

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
/**
 * 求子数组的最大和
 */
#include <stdlib.h>
#include <stdio.h>

bool func(const int inArr[], const size_t inLength, int &outResult)
{
    if (inArr == NULL || inLength == 0)
    {
        return false;
    }

    int tmpSum = 0;
    outResult     = 0;

    /// 只累加正和
    for (size_t i = 0; i < inLength; i++)
    {
        tmpSum += inArr[i]; // 累加
        tmpSum = tmpSum < 0 ? 0 : tmpSum;   // 和小于0就清零
        outResult = tmpSum > outResult ? tmpSum : outResult;    // 判断最大值
    }

    /// 如果所有元素都是负数
    if (0 == outResult)
    {
        outResult = inArr[0];
        for (size_t i = 1; i < inLength; i++)
        {
            outResult = inArr[i] > outResult ? inArr[i] : outResult;
        }
    }

    return true;
}

int main()
{
    const size_t SIZ       = 10;
    const int    arr[SIZE] = {-2, 4, 1, -5, 5, -1, 5, 5, 1, -10};

    int largest = 0;
    if (func(arr, SIZE, largest))
    {
        printf("最大和:%d\n", largest);
    }
    else
    {
        printf("查找失败\n");
    }

#ifdef _DEBUG
    system("pause");
#endif;

    return EXIT_SUCCESS;
}

 

posted on 2014-09-26 10:36  3th  阅读(81)  评论(0编辑  收藏  举报