Description
输入一个长度为n的整数序列,从中找出一段不超过m的连续子序列,使得整个序列的和最大。
例如
1
,
−
3
,
5
,
1
,
−
2
,
3
1,-3,5,1,-2,3
1,−3,5,1,−2,3
当
m
=
4
m=4
m=4时,
S
m
a
x
=
5
+
1
−
2
+
3
=
7
S_{max}=5+1-2+3=7
Smax=5+1−2+3=7
当
m
=
2
m=2
m=2或
m
=
3
m=3
m=3时,
S
m
a
x
=
5
+
1
=
6
S_{max}=5+1=6
Smax=5+1=6
Input
第一行两个数
n
,
m
n,m
n,m
第二行有
n
n
n个数,要求在
n
n
n个数找到最大子序和。
Output
一个数,即最大子序和。
Sample Input
6 4
1 -3 5 1 -2 3
Sample Output
7
Hint
n , m ≤ 300000 n,m \leq 300000 n,m≤300000
分析
此题求解目标是最大区间和,不难想到将区间和转化为前缀和之差
对于每个
s
i
s_i
si 只需在
[
i
−
m
,
i
−
1
]
[i-m,i-1]
[i−m,i−1]这个区间内找最小的
s
j
s_j
sj
所以用单调队列来维护这个最小值
标程
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
long long s[300005] = {0};
deque<int> q;
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
int n,m;
scanf("%d%d",&n,&m);
long long maxs = -9999999999ll;
for(int i = 1;i <= n;i++)
{
int k;
scanf("%d",&k);
s[i] = s[i-1] + k;
}
q.push_back(0);
for(int i = 1;i <= n;i++)
{
maxs = max(maxs,s[i] - s[q.front()]);
while(!q.empty() && s[q.back()] > s[i])
q.pop_back();
if(!q.empty() && q.front() < i - m + 1)
q.pop_front();
q.push_back(i);
}
cout<<maxs;
return 0;
}