最大子数组和

#include <iostream>
using namespace std;

struct MaxRangResult
{
    int max_;
    int start_;
    int end_;
};

MaxRangResult FindMaxRang(const vector<int>& nums)
{
    MaxRangResult result{0, 0, 0};
    int sum = 0;
    int current = 0;

    for (int i = 0, size = nums.size(); i < size; ++i)
    {
        if (sum < 0)
        {
            sum = nums[i];
            current = i;
        }
        else
        {
            sum += nums[i];
        }
        if (result.max_ < sum)
        {
            result.max_ = sum;
            result.start_ = current;
            result.end_ = i;
        }
    }

    return result;
}

int main()
{
    vector<int> nums{3, -4, 1, 3};
    MaxRangResult result = FindMaxRang(nums);

    getchar();
    return 0;
}

 

posted @ 2017-02-26 22:22  略加思索的河马  阅读(120)  评论(0编辑  收藏  举报