2017年5月校赛赛前练习 最大连续区间和

Problem A: 最大连续区间和

Time Limit: 1 Sec  Memory Limit: 32 MB
Submit: 43  Solved: 2
[Submit][Status]

Description

你的任务是找出一串数字中,哪一些连续数字之和最大,并输出这个和。

例如:输入的一串数字为“-1 2 -3 4 2 -5 6 -5”,你需要输出“7”(在该输入中,和最大的一些连续数字为“4 2 -5 6”)。

Input

第一行为测试用例的组数。

每组输入包括两行,第一行为一串数的个数n (n<=10^5)。

随后一行为该串数字,每两个数中间会用空格隔开。(题目保证每个数的绝对值小于10^9)

Output

对每一组测试用例,输出最大和是多少

Sample Input

23-1 -2 -38-1 2 -3 4 2 -5 6 -5

Sample Output

-17

HINT

[Submit][Status]
思路:
方法一:分治法
方法二:maxn为最大连续数字之和,temp为当前连续数字之和
方法三:用a[i]表示以第i个数字结尾的最大连续数字和,a数组中最大的数即为结果。
注意:虽然每个数字在int表示范围内,但运算后(相加)的数字可能大于int

欢迎交流:
下面的方法二是正确的,我写的方法三有点点错误,希望大神给菜鸟我指出,万分感谢

方法二:
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;

//const int MAXN = 100000 + 5;
typedef  long long ll;

int main()
{

	int t;
	scanf("%d", &t);
	while (t--)
	{
		int n;
		scanf("%d", &n);
		ll maxn=0, temp=0;//maxn为最大连续数字之和,temp为当前连续数字之和
		for (int i = 0; i <n; i++)
		{

			int c;
			scanf("%d", &c);

			if (i == 0) 
			{ 
				maxn = c; 
				
				if (c < 0)temp = 0;
				else temp = c; 
			}
			else
			{
				temp += c;
				if (temp>maxn)maxn = temp;
				else if (temp < 0)temp = 0;//假设temp为前i个数字和,因为temp为0,那么前i+1个的最大数字和一定是第i+1个数字
			}

		}
		printf("%lld\n", maxn);
	}

	return 0;
}



方法三:我写的方法三有点点错误,希望大神给菜鸟我指出,万分感谢
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;

typedef long long ll;

const int MAXN = 100000 + 5;
ll r[MAXN];//用r[i]表示以第i个数字结尾的最大连续数字和,r数组中最大的数即为结果。

bool cmp(int a, int b)
{
	return a > b;
}

int main()
{
	
	int t;
	scanf("%d", &t);
	while (t--)
	{
		memset(r, 0, sizeof(r));
		int n;
		scanf("%d",&n);
		for (int i = 0; i <n; i++)
		{
			
			ll c;
			scanf("%lld",&c);
			if (i==0) r[i] = c;
			else 
			 r[i] =max(c,c+r[i-1]);
		}
		sort(r,r+n,cmp);
		printf("%lld\n",r[0]);
	}
	


	return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章