码迷,mamicode.com
首页 > 编程语言 > 详细

[算法练习]序列最大和

时间:2015-10-20 19:23:38      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

题目说明:

输入一个数列(包含正负数),求和是最大的连续子序列。例如{5,-3,4,2}的最大子序列就是 {5,-3,4,2}。

 

程序代码:

#include <gtest/gtest.h>
using namespace std;

int MaxSumOfSequence(int* pData, int nLength, int& nBegin, int& nEnd)
{
    if (!pData || !nLength)
    {
        return 0;
    }

    int nMaxSum = 0;
    int nCurrVal = 0;
    int nCurrBegin = 0;

    for (int i = 0; i < nLength; ++i)
    {
        nCurrVal += pData[i];
        if (nCurrVal >= nMaxSum)
        {
            nMaxSum = nCurrVal;
            nBegin = nCurrBegin;
            nEnd = i;
        }

        if (nCurrVal < 0)
        {            
            nCurrVal = 0;
            nCurrBegin = i+1;
        }
    }

    return nMaxSum;
}

TEST(Algo, tMaxSumOfSequence)
{
    //     
    // 5,-6,4,2    
    // 5,-4,4,2    
    // 5,4,-10,2    
    
    int Data1[] = {5,-6,4,2};
    int nBegin = 0;
    int nEnd = 0;

    ASSERT_EQ(MaxSumOfSequence(Data1,4,nBegin,nEnd),6);
    ASSERT_TRUE(nBegin==2 && nEnd==3);

    int Data2[] = {5,-4,4,2};
    ASSERT_EQ(MaxSumOfSequence(Data2,4,nBegin,nEnd),7);
    ASSERT_TRUE(nBegin==0 && nEnd==3);

    int Data3[] = {5,4,-10,2};
    ASSERT_EQ(MaxSumOfSequence(Data3,4,nBegin,nEnd),9);
    ASSERT_TRUE(nBegin==0 && nEnd==1);
}

[算法练习]序列最大和

标签:

原文地址:http://www.cnblogs.com/Quincy/p/4895621.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!