最大序列和

本文介绍了一种使用动态规划解决最大子序列和问题的方法。通过定义子状态和转移方程,避免了直接两次遍历的时间超限问题。文章详细解释了动态规划的过程,并提供了一个完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
#include<iostream>
#include<vector>
#include<set>
#include<queue>
#include<map>
using namespace std;
 
typedef long long LL;
const int N=1e5+10,mod=1e6;
const int MAX = 1e8 + 10 ;

/*直接两次遍历的话肯定是会超过时间的,
典型的动态规划;
子状态:
1.取a[i] ,dp[i] = dp[i-1] + a[i] ;
2.不取a[i] , 因为要求连续的序列所以新的值就是a[i] ;
所以转移方程:
dp[i] = max(dp[i-1] + a[i] , a[i]) ;
*/

LL a[1000010]; //记录输入的值
LL dp[1000100] ; //动态规划的方程

LL max(LL n , LL m){
	return n > m ? n : m ;
}

int main(){
	int n ;
	while(cin >> n){
		for(int i = 1 ; i <= n ; i++){
			cin >> a[i] ;
		}
		
		LL Max ;

    
		for(int i = 1 ; i <= n ; i++){
			dp[i] = max(dp[i-1] + a[i] , a[i]) ;
			if(i == 1){
				Max = dp[1] ;
			}
			if(dp[i] > Max ) {
				Max = dp[i] ;
			}
		}
		
		/*不懂的同学可以把这个加上试试
                for(int i = 1 ; i <= n ; i++){
			cout << dp[i] << ' '  ;
		}
		cout <<endl; */
		
		cout << Max <<endl;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值