分而治之求解最大子列

  分而治之求解最大子列和,虽然并不是求解这个问题的最优解,但仍然是不容忽略的。它最主要提供了一种思想:将很大的问题分解成一个个小问题进行求解。

  1.将数列划分成维度为1的一个个小单元,如果<0那么便返回0,因为就算将这个负数返回了也只是减少大小,如果>0,那么便会返回它。

  2.下面就开始向左扫描向右扫描,求出跨越分界线的最大子列。

  3.最后和之前求出的左子列和右子列最大和进行比较返回最大的一个,进行下一次的迭代。

inline int maxf(int _1,int _2,int _3)
{
	if(_1>_2&&_1>_3)
		return _1;
	else if(_2>_1&&_2>_3)
		return _2;
	return _3;
}
int merge(int a[],int left,int right)
{
	int temp_max_sum_left,temp_max_sum_right;
	int max_sum_left,max_sum_right;
	int middle;
	int max_left,max_right;
	if(left==right)
	{
		if(a[left]>=0)
			return a[left];
		else
			return 0;
	}
	middle=(left+right)/2;
	max_left=merge(a,left,middle);
	max_right=merge(a,middle+1,right);
	int i;
	temp_max_sum_left=0;temp_max_sum_right=0;
	max_sum_left=0;max_sum_right=0;
	for(i=middle;i>=left;--i)
	{
		temp_max_sum_left+=a[i];
		if(temp_max_sum_left>max_sum_left)
			max_sum_left=temp_max_sum_left;
	}
	for(i=middle+1;i<=right;++i)
	{
		temp_max_sum_left+=a[i];
		if(temp_max_sum_left>max_sum_left)
			max_sum_left=temp_max_sum_left;
	}
	return maxf(max_left,max_right,max_sum_left+max_sum_right);
}

猜你喜欢

转载自blog.csdn.net/qq_41657315/article/details/79887331