洛谷P1115 最大子段和

很纳闷这道题的标签为什么是DP

说实话我被做题不仔细看题的毛病给坑了一下下

我想大家都知道是哪一个点

昂,就是第二个测试点,第二个测试点全是$<$0的数QAQ

然后题目要求我们的子串长度$\geq$1

于是第一次我就光荣的WA了


思路:

维护一个sum数组,用来记录序列的最大值

维护一个x数组,用来输入

为了解决我们上述的问题,我们还要:

维护一个minn数组,用来记录序列最大值(特判全部小于0的情况)

维护一个zero数组,用来判断序列中有没有0

然后:

就解决这个问题了!!!


代码:
code:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std ;
int read() ;
int main() {
	int n ;
	n = read() ;
	int x ;
	int zero = 0 ;
	int sum = 0 ;
	int maxx = 0 ;
	int minn = -0x7ffff ;
	for(int i = 1 ; i <= n ; i ++){
		x = read() ;
		if(!x) zero = 1 ;
		minn = max(minn,x) ;
		if(sum < 0) {sum = 0 ;}
		sum += x ;
		maxx = max(maxx,sum) ;
	}
	if(!maxx&&!zero) maxx = minn ;
	cout << maxx << endl ;
	return 0;
}
int read() {
	int x = 0;int f = 1 ;char s = getchar() ;
	while(s>'9'||s<'0') {if(s=='-')f=-1;s=getchar();}
	while(s<='9'&&s>='0') {x=x*10+(s-'0');s=getchar();}
	return x*f ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值