最大字段和

给定n个整数(可能为负数组成的序列a[1],a[2],a[3],a[4],,,,,,,,,,a[n],求该序列和的字段和的最大值
#include
using namespace std;
int MaxSubSum(int *a, int left, int right);//分治法求最大子段和
int main()
{
	int n, result;
	cout << "请依次输入序列中元素的个数: " << endl;
	cin >> n;
	int *a = new int[n];
	cout << "请依次输入序列中的各元素值:" << endl;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	result = MaxSubSum(a, 0, n - 1);
	cout << "最大字段的和为" << result<< endl;
	return 0;
}
int MaxSubSum(int  *a, int left, int right)
{
	int maxSum = 0;
	if (left == right)
		return (a[left]>0 ? a[left] : 0);
	int middle = (left + right) / 2;
	int leftSum = MaxSubSum(a, left, middle);
	int rightSum = MaxSubSum(a, middle + 1, right);
	int i, lefs = 0, rigs = 0,temSum = 0;
	for (i = middle; i >= left; --i)
	{
		temSum += a[i];
		lefs = (temSum > lefs) ? temSum : lefs;

	}
	temSum = 0;
	for (i = middle + 1; i <= right; ++i)
	{
		temSum += a[i];
		rigs = (temSum > rigs) ? temSum : rigs;

	}
	maxSum = lefs + rigs;
	if (leftSum > maxSum)
		maxSum = leftSum;
	if (rightSum > maxSum)
		maxSum = rightSum;
	return maxSum;
}

你可能感兴趣的:(最大字段和)