PAT结构与算法7-1 最大子列和问题 (20 分)(低耗迭代)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40946921/article/details/99688714

7-1 最大子列和问题 (20 分)

给定K个整数组成的序列{ N​1​​, N​2​​, ..., N​K​​ },“连续子列”被定义为{ N​i​​, N​i+1​​, ..., N​j​​ },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。

本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:

  • 数据1:与样例等价,测试基本正确性;
  • 数据2:102个随机整数;
  • 数据3:103个随机整数;
  • 数据4:104个随机整数;
  • 数据5:105个随机整数;

输入格式:

输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。

输出格式:

在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。

输入样例:

6
-2 11 -4 13 -5 -2

输出样例:

20
#include <iostream>
using namespace std;
int main() {
	int n, sum = INT32_MIN, pre = 0, now;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &now);
		if (pre > 0)
			now += pre;
		if (now > sum)
			sum = now;
		pre = now;		//迭代
	}
	printf("%d\n", sum);
	return 0;
}

 暴力版本:

#include <iostream>
#include <vector>
using namespace std;
int main() {
	int n, sum, max = INT32_MIN;
	scanf("%d", &n);
	vector<int> vc(n);
	for (int i = 0; i < n; ++i) {
		scanf("%d", &vc[i]);
		sum = vc[i];
		for (int j = i - 1; j >= 0 && sum > 0; --j) {	//当和小于0 时,不用继续求解,这串无意义
			sum += vc[j];
			if (sum > max)
				max = sum;
		}
	}
	printf("%d", max > 0 ? max : 0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/99688714
今日推荐