码迷,mamicode.com
首页 > 其他好文 > 详细

53.Maximum Subarray(法1线性扫面法2分治法)

时间:2015-02-02 23:16:28      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:

Find the contiguous subarray within an array (containing at least onenumber) which has the largest sum.

For example, given the array [?2,1,?3,4,?1,2,1,?5,4],
the contiguous subarray [4,?1,2,1] has thelargest sum = 6.

click to showmore practice.

HideTags

 Divide and Conquer Array Dynamic Programming

 

 

#include<iostream>
using namespace std;

//取大值
int max(int a, int b, int c)
{
	if (a > b)
		if (a > c)
			return a;
		else
			return c;
	else if (c > b)
		return c;
	return b;
}

//flag=1,返回与A同尾的子数组的最大值,flag=0,返回与A同头的子数组的最大值
int maxSideArray(int *A, int n, int flag)
{
	if (flag)//返回与A同尾的子数组的最大值
	{
		int sum = 0;
		int maxsum = A[n - 1];
		for (int i = n - 1; i >= 0; i--)
		{
			sum += A[i];
			if (sum > maxsum)
				maxsum = sum;
		}
		return maxsum;
	}
	else//返回与A同头的子数组的最大值
	{
		int sum = 0;
		int maxsum = A[0];
		for (int i = 0; i < n; i++)
		{
			sum += A[i];
			if (sum > maxsum)
				maxsum = sum;
		}
		return maxsum;
	}

}

//法2:分而治之
int maxSubArray2(int A[], int n)
{
	if (n == 1)
		return *A;
	//左半部分最大值,有半部分最大值,跨过中线的最大值:三个值取最大
	return max(maxSubArray2(A, n / 2), maxSubArray2(A + n / 2, n - n / 2), maxSideArray(A, n / 2, 1) + maxSideArray(A + n / 2, n - n / 2, 0));
}

//法1:线性扫描
int maxSubArray(int A[], int n)
{
	int sum = 0;
	int maxsum = A[0];
	for (int i = 0; i < n; i++)
	{
		sum += A[i];
		if (sum > maxsum)
			maxsum = sum;
		if (sum < 0)
			sum = 0;
	}
	return maxsum;
}


void main()
{
	int A[] = { 1, -8, 6, 3, -1, 5, 7, -2, 0, 1 };
	int B[] = { -2, 1 };
	cout << maxSubArray(A, 10) << endl;
	cout << maxSubArray(B, 2) << endl; 
	cout << maxSubArray2(A, 10) << endl;
	cout << maxSubArray2(B, 2) << endl;
	system("pause");
}


53.Maximum Subarray(法1线性扫面法2分治法)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43415633

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!