感谢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;
}

相关文章:

  • 2021-11-05
  • 2021-10-15
  • 2021-07-01
  • 2022-03-04
  • 2021-10-03
  • 2021-09-24
  • 2022-12-23
  • 2022-01-18
猜你喜欢
  • 2022-01-06
  • 2022-01-17
  • 2022-01-07
  • 2022-02-22
  • 2021-09-17
  • 2021-11-29
  • 2022-03-06
相关资源
相似解决方案