求子數組的最大和要求O(n)

//求子數組的最大和

//輸入一個整形數組,有整數也有負數,數組中連續一個或多個子數組,每個子數組都有一個和,求所有子數組的和的最大值,要求時間複雜度O(n)



#include<iostream>

int GetMax( int * arr)
{
	int max = arr[0];
	for (int i = 1; i < 10; i++)
	{
		if (max < arr[i])
		{
			max = arr[i];
		}
	}	return max;
}

int getMaxSum(int * arr)
{
	int result = 0;
	int tmp = 0;
	for (int i = 0; i < 10; i++)
	{
		if (tmp>0)
		{
			tmp += arr[i];
		}
		else
		{
			tmp = arr[i];
		}
		if (tmp > result)
			result = tmp;

	}	return result;
}

using namespace std;

void main()
{
	int arr[10] = { 1, -3, 8, -6, 2, -3,4, 8,  -11, 12 };
	int max = GetMax( arr);
	if (max <= 0)
	{
		cout << "最大子數組和爲" << max;
		cin.get();
		return;
	}
	int result = getMaxSum(arr);

	cout << "最大子數組和爲" << result;

	cin.get();
}


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