求子数组的最大和

题目:求子数组的最大和

要求:1、输入一个整形数组,数组里有正数也有负数。

         2、数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

         3、求所有子数组的和的最大值。要求时间复杂度为O(n)。

举例:输入数组为1, -2, 3, 10, -4, 7, 2, -5。和的最大子数组为 3, 10, -4, 7, 2。即输出和为18。

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

int FindMaxSubSum(int arr[], int length)
{
    int sum = 0;
    int temp = 0;
    for (int i = 0; i < length; i++)
    {
        if (temp <= 0)
        {
            temp = arr[i];
        }
        else
        {
            temp += arr[i];
        }
        if (temp > sum)
        {
            sum = temp;
        }
    }

    return sum;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};
    cout<<FindMaxSubSum(arr, sizeof(arr) / sizeof(int))<<endl;
    return 0;
}

运行界面如下:

原文地址:https://www.cnblogs.com/venow/p/2649699.html