首页 > 代码库 > 【动态规划】【单调队列】tyvj1305 最大子序和

【动态规划】【单调队列】tyvj1305 最大子序和

http://blog.csdn.net/oiljt12138/article/details/51174560

单调队列优化dp

#include<cstdio>
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
int n,m;
ll a[300100],ans;
deque<int>q;
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;++i){
		cin>>a[i];
	}
	for(int i=2;i<=n;++i){
		a[i]+=a[i-1];
	}
	q.push_front(0);
	for(int i=1;i<=n;++i){
		while((!q.empty()) && a[q.front()]>=a[i]){
			q.pop_front();
		}
		q.push_front(i);
		while(q.back()<i-m){
			q.pop_back();
		}
		ans=max(ans,a[i]-a[q.back()]);
	}
	cout<<ans<<endl;
	return 0;
}

【动态规划】【单调队列】tyvj1305 最大子序和