PAT1007 Maximum Subsequence Sum (25)(最大连续和)

50 篇文章 0 订阅

这题没什么好说的就是一个最大连续和的裸题,只要掌握dp[i]=max(dp[i-1],0)+num[i]即可,记录一下主要是因为我自己写的时候边界条件没处理好,也就是dp[i-1]这里对于0的处理,所以尽量少用dp[i-1]这种形式,用一个变量存就可以了。

/*自己写的不太好*/
#include<string>
#include<cstdlib>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;

const int maxn = 10010;

int main() {
	int dp[maxn], a[maxn];
	int m;
	bool flag = true;
	cin >> m;
	int first = 0, last = m - 1;
	for (int i = 0; i < m; i++)
		cin >> a[i];
	int tem = 0;
	int res = -1;
	int temp = 0;
	for (int i = 0; i < m; i++) {
		if (tem < 0) {
			temp = i;
			tem = a[i];
		}
		else
			tem = tem + a[i];
		if (tem > res) {
			res = tem;
			last = i;
			first = temp;
		}
	}
	if (res < 0) {
		res = 0;
		cout << res << " " << a[0] << " " << a[m - 1] << endl;
	}
	else
		cout << res << " " << a[first] << " " << a[last] << endl;
	return 0;
}
/*参考网上的代码*/
#include<string>
#include<cstdlib>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;

int main() {
	int n;
	cin >> n;
	vector<int> v(n);	//这里vector的使用可以学习一下
	int sum = -1, temp = 0, left = 0, right = n - 1, tempindex = 0;
	for (int i = 0; i < n; i++) {
		scanf("%d", &v[i]);
		temp += v[i];
		if (temp < 0) {
			temp = 0;
			tempindex = i + 1;	//下一个才能作为左边界
		}
		else if (temp>sum) {
			sum = temp;
			left = tempindex;
			right = i;
		}
	}
	if (sum < 0) sum = 0;
	cout << sum << " " << v[left] << " " << v[right] << endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值