劍指offer-獲取數組中子序列之和最大值

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//

/*
Q:
    連續子數組的最大和:
        輸入一個整型數組,數組中有正數也有負數,數組中一個或者連續多個數組組成一個子數組。求所有子數組
        中的和最大值。
S:
    這裏採用動態規劃的思想:
        假設f(i)表示第i個數結尾的子數組的最大和,那麼要求可以得到如下的遞推式:
            f(i) = f(i-1) + data[i], if f(i-1) > 0 && i !=0
            f(i) = data[i]          , if f(i-1) <=0 || i == 0

*/

#include <iostream>
#include <cstdio>
#include <cstdlib>

int getGreatestSumOfSubArr(int*numbers, int length)
{
    if(numbers == nullptr || length <= 0)
        return 0;
    
    int curSum = 0;
    int maxSum = -99999;
    for(int i = 0; i < length; ++i)
    {
        if(curSum <= 0)
        {
            curSum = numbers[i];
        }else{
            curSum += numbers[i];
        }
        if(curSum > maxSum)
            maxSum = curSum;
    }
    return maxSum;
}

void test_1()
{
    std::cout << "Test 1" << std::endl;
    int numbers[] = {1,-2,3,10,-4,7,2,-5};
    std::cout << "Found max_sum = " << getGreatestSumOfSubArr(numbers, 8) << std::endl;
}

void test_2()
{
    std::cout << "Test 2" << std::endl;
    int numbers[] = {-1,-4,-1,-4,-8,-4,-19,-10};
    std::cout << "Found max_sum = " << getGreatestSumOfSubArr(numbers, 8) << std::endl;
}

void test_3()
{
    std::cout << "Test 3" << std::endl;
    int numbers[] = {1,2,5,4,1,7,9,4};
    std::cout << "Found max_sum = " << getGreatestSumOfSubArr(numbers, 8) << std::endl;
}

void test_4()
{
    std::cout << "Test 4" << std::endl;
    int*numbers = nullptr;
    std::cout << "Found max_sum = " << getGreatestSumOfSubArr(numbers, 8) << std::endl;
}

void test_getGreatestSumOfSubArr()
{
    test_1();
    test_2();
    test_3();
    test_4();
}

int main(int argc, char**argv)
{
    test_getGreatestSumOfSubArr();

    return 0;
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章