《编程之美》读书笔记(十二):“求数组的子数组之和的最大值”扩展问题

感谢azuryy为大家分享《编程之美》第2.14节扩展问题2的答案,原博客地址:http://hi.baidu.com/azuryy/blog/item/c7b7f7ddaa9f49df8d102916.html

 

下面的代码,如果存在多个最大的子序列,则只返回最前面的。
如果数组全为负数,比如-3, -2, -1, -8, 程序返回 -1,起始,终止位置都是2
int MaxNumber(int* A){
    int nStart = A[0];
    int nAll = A[0];
    int tmpStart = 1;
    int si = 1 ,    ei = 1;
    for( int i = 1; i < n; i++)
    {
        if (nStart < 0)
        {
            nStart = 0 ;           
            tmpStart = i+1;
        }
        nStart += A[i];
        if (nStart > nAll)
        {
            ei = i+1;
            nAll = nStart;
            si = tmpStart;
        }
    }
    return nAll;
}

posted @ 2008-08-05 10:19  博文视点  阅读(1521)  评论(0编辑  收藏  举报