Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >跨站数据

实例1.1 最大子列和问题

**

简洁版本:

**

#include<stdio.h>
#define MAX_size 100000
int Findmaxsum(int array[], int numsize);
int main()
{
	int array[MAX_size];
	int size;
	int maxsum = 0;
	scanf("%d", &size);
	getchar();
	for (int i = 0;i < size;i++)
	{
		scanf("%d", &array[i]);
		getchar();
	}
	maxsum = Findmaxsum(array, size);
	printf("%d\n", maxsum);
	return 0;
}
int Findmaxsum(int array[], int numsize)
{
	int temp_array[MAX_size];
	int temp = 0;
	int maxsum = 0;
	int count = 0;
	for (int i = 0;i < numsize;i++)
	{
		if (array[i] >= 0)
			break;
		else count++;
	}
	if (count == numsize)
		return 0;


	for (int i = 0;i < numsize;i++)
	{
		temp <= 0 ? (temp_array[i] = array[i], temp = array[i]) : (temp + array[i] > 0 ? (temp_array[i] = temp + array[i], temp = temp_array[i]) : (temp_array[i] = array[i], temp = array[i]));
	}

	for (int i = 0;i < numsize;i++)
	{
		maxsum = temp_array[i] > maxsum ? temp_array[i] : maxsum;
	}
	return maxsum;
}

好理解版本:

#include<stdio.h>
#define MAX_size 100000
int Findmaxsum(int array[], int numsize);
int main()
{
	int array[MAX_size];
	int size;
	int maxsum = 0;
	scanf("%d", &size);
	getchar();
	for (int i = 0;i < size;i++)
	{
		scanf("%d", &array[i]);
		getchar();
	}
	maxsum = Findmaxsum(array, size);
	printf("%d\n", maxsum);
	return 0;
}
int Findmaxsum(int array[], int numsize)
{
	int temp_array[MAX_size];
	int temp = 0;
	int maxsum = 0;
	int count = 0;
	for (int i = 0;i < numsize;i++)
	{
		if (array[i] >= 0)
			break;
		else count++;
	}
	if (count == numsize)
		return 0;


	for (int i = 0;i < numsize;i++)
	{
		if (temp <= 0)
		{
			temp_array[i] = array[i];
			temp = array[i];
		}
		else {
			if (temp + array[i] > 0)
			{
				temp_array[i] = temp + array[i];
				temp = temp_array[i];
			}
			else {
				temp_array[i] = array[i];
				temp = array[i];
			}
		}
	}
	for (int i = 0;i < numsize;i++)
	{
		maxsum = temp_array[i] > maxsum ? temp_array[i] : maxsum;
	}
	return maxsum;
}

代码实现的效果是一样的,而且代码也是“一样”的,只是把if语句都换成了三目运算了。虽然不好看,但是简洁呀,哈哈哈哈嗝~。

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: Docker镜像篇(6) - 镜像仓库 - dockerhub

下一篇: 中小企业数字化,平安涉足政企的切口

精华推荐