最大子序和

https://www.acwing.com/activity/content/problem/content/1458/1/

\(用单调队列得到[i-m,\ i-1]区间中最小的是s[j],\ s[i]-s[j]即为所求\)

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 3e5 + 10;
int q[N];
int s[N];

int main() {
    IO;
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        cin >> s[i];
        s[i] += s[i - 1];
    }
    int hh = 0, tt = 0, ans = -inf;
    for (int i = 1; i <= n; ++i) {
        if (q[hh] < i - m) ++hh;
        ans = max(ans, s[i] - s[q[hh]]);
        while (hh <= tt && s[q[tt]] >= s[i]) --tt;
        q[++tt] = i;
    }
    cout << ans << '\n';
    return 0;
}

posted @ 2021-02-04 01:51  phr2000  阅读(42)  评论(0编辑  收藏  举报