首页 > 其他 > 详细

连续子数组的最大和

时间:2014-03-15 16:43:40      阅读:348      评论:0      收藏:0      [点我收藏+]
/*********************************************************************
题目:输入一个整型数组,数组里有整数也有负数。数组中一个或连续的多个整数
组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(N)。
*********************************************************************/
#include<iostream>
using namespace std;

int greatestSumOfSubArray(int* arr, int length)
{
	if(arr == NULL || length<=0)
		throw exception("Invalid input!\n");

	int sum = arr[0];
	int greatestSum = arr[0];

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

void test()
{
	int arr[8] = {1,-2,3,10,-4,7,2,-5};
	cout << greatestSumOfSubArray(arr,8) << endl;

}
void test1()
{
	cout << greatestSumOfSubArray(NULL,0) << endl;

}
int main()
{
	try{
		test();
		test1();
	}
	catch(exception ex)
	{
		cout << ex.what()<<endl;
	}
	return 0;
}
//时间复杂度为O(N)
==参考剑指offer

连续子数组的最大和,布布扣,bubuko.com

连续子数组的最大和

原文:http://blog.csdn.net/walkerkalr/article/details/21276317

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!