求子数组的最大和

题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。

// 求子数组的最大和.cpp : Defines the entry point for the console application.
//
/*
题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。

*/

#include "stdafx.h"
#include <iostream>
using namespace std;
void maxSumChildArray(int a[],int count)
{
	int	curSum = 0;
	int maxSum = 0;
	for (int i=0; i<count; i++)
	{
		curSum += a[i];
		if (curSum < 0)
		{
			//如果前面的值加起来小于0的话,重新开始相加
			curSum = 0;
		}
		if (curSum > maxSum)
		{
			//将最大的和值赋值给maxSum
			maxSum = curSum;
		}
	}
	//若数组中所有的值都为负数,则curSum=0,取负数的最大值
	if (curSum == 0)
	{
		maxSum = a[0];//将数组中第一个值赋值给maxSum
		for (int i=1; i<count; i++)
		{
			if (maxSum < a[i])
			{
				maxSum = a[i];
			}
		}
	}
	cout << "最大子数组和为:" << maxSum << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int a[] = {1, -2, 3, 10, -4, 7, 2, -5};
	maxSumChildArray(a,8);
	system("pause");
	return 0;
}

 

posted on 2013-11-04 15:43  学习程序  阅读(146)  评论(0)    收藏  举报

导航