数据结构与算法--最大子列和代码汇总(C语言)

/*求最大子列和算法比较*/
#include
#define N 10

int MaxSubseqSum1(int a[], int n);		//n^3的算法复杂度
int MaxSubseqSum2(int a[], int n);		//n^2的算法复杂度
int MaxSubseqSum3(int a[], int n);		//nlog n的算法复杂度
	static int MaxSubSum(int a[],int left,int right);	
	int Max3(int a, int b, int c);
int MaxSubseqSum4(int a[], int n);		//nd的算法复杂度 

int main(int argc, char const *argv[])
{
	int a[N] = {1,-2,3,-4,5,-6,7,-8,9,-10};

	int a1=MaxSubseqSum1(a, N);
	printf("最大子列和为:%d\n", a1);

	int a2 = MaxSubseqSum2(a, N);
	printf("最大子列和为:%d\n", a2);

	int a3 = MaxSubseqSum3(a, N);
	printf("最大子列和为:%d\n", a3);

	int a4 = MaxSubseqSum4(a, N);
	printf("最大子列和为:%d\n", a4);

	return 0;
}

int MaxSubseqSum1(int a[], int n)		//三重循环,算法思想最简单
{
	int i, j;
	int max = 0;
	for (i = 0; i < n; i++)
	{
		for (j = i; j < n; j++)
		{
			int ThisMax = 0;
			int k;
			for (k = i; k <= j; k++)
			{
				ThisMax += a[k];
			}
			if (ThisMax > max)
				max = ThisMax;
		}
	}

	return max;
}

int MaxSubseqSum2(int a[], int n)		//省去第三重循环
{
	int i, j;
	int max = 0;
	for (i = 0; i < n; i++)
	{
		for (j = i; j < n; j++)
		{
			int ThisMax = 0;
			ThisMax += a[j];
			if (ThisMax > max)
				max = ThisMax;
		}
	}
	return max;
}

int MaxSubseqSum3(int a[], int n)
{
	return MaxSubSum(a, 0, n-1);
}
static int MaxSubSum(int a[], int left, int right)
{
	int MaxLeftSum, MaxRightSum;		//左右两侧的对大子列和
	int MaxLeftBorderSum, MaxRightBorderSum;		//由分界处向左右两侧的最大和子列和
	int LeftBorderSum=0, RightBorderSum=0;			
	int Center, i;
	
	if (left == right)
		if (a[left] > 0)
			return  a[left];
		else
			return  0;

	Center = (left + right) / 2;
	MaxLeftSum = MaxSubSum(a, left, Center);
	MaxRightSum = MaxSubSum(a, Center+1, right);		//注意从center+1开始计算,第一次写成center,导致程序死循环
	for (i = Center; i >= left; i--)
	{
		MaxLeftBorderSum = 0;
		LeftBorderSum += a[i];
		if (LeftBorderSum > MaxLeftBorderSum)
			MaxLeftBorderSum = LeftBorderSum;
	}
	for (i = Center+1; i <=right ; i++)                //修正,应从center+1开始
	{
		MaxRightBorderSum = 0;
		RightBorderSum += a[i];
		if (RightBorderSum > MaxRightBorderSum)
			MaxRightBorderSum = RightBorderSum;
	}

	return Max3(MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum);		//左右侧最大子列和与从分界处左右最大子列和的和进行大小比较

}
int Max3(int a, int b, int c)
{
	if (a >= b && a >= c)
		return a;
	else if (b >= a && b >= c)
		return b;
	else
		return c;
}

int MaxSubseqSum4(int a[], int n)		//动态规划,实时给出当前输入数组的最大子列和
{
	int max, ThisMax;
	max = ThisMax = 0;
	int i;
	for (i = 0; i < n; i++)
	{
		ThisMax += a[i];
		if (ThisMax > max)
			max = ThisMax;
		else if (ThisMax < 0)
			ThisMax = 0;
	}

	return max;
}

本文对数据结构与算法中第一个实例进行了代码的总结,基于c语言进行编写,程序在vs2017上运行正常。

你可能感兴趣的:(基础算法理解)