输入一个长度为n的整数序列,从中找出一段长度不超过m的连续子序列,使得子序列中所有数的和最大。
第一行输入两个整数n,m。
第二行输入n个数,代表长度为n的整数序列。
同一行数之间用空格隔开。
输出一个整数,代表该序列的最大子序和。
1≤n,m≤300000
6 4
1 -3 5 1 -2 3
7
算法:单调队列
#include<iostream> #include<queue> #include<algorithm> #include<limits.h> using namespace std; const int N=300010; typedef long long LL; LL s[N]; int n,m; deque<int>q; int main(void){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>s[i]; s[i]+=s[i-1]; } q.push_front(0); LL res=INT_MIN; for(int i=1;i<=n;i++){ if(i-q.front()>m)q.pop_front(); res=max(res,s[i]-s[q.front()]); while(q.size()&&s[q.back()]>=s[i])q.pop_back(); q.push_back(i); } cout<<res<<endl; return 0; }
原文:https://www.cnblogs.com/programyang/p/11209049.html