AcWing. 135. 最大子序和

题目链接

单调队列

  • 使用前缀和预处理
  • 使用队列维护长度为m的集合
  • 从队列中根据单调性在 O ( 1 ) O(1) O(1)的时间内求得极值
#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
using namespace std;
typedef long long LL;
const int N = 3e5+6;
int q[N];
LL s[N];
int main()
{
    
    
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i ++ ){
    
    
        scanf("%lld", &s[i]);
        s[i] += s[i-1];
    }
    memset(q, 0, sizeof q);
    LL res = INT_MIN;
   
    int hh = 0, tt = 0;
    for (int i = 1; i <= n; i ++ ){
    
    
        if(i - q[hh] > m) hh++;
        res = max(res, s[i] - s[q[hh]]);
        while(hh<=tt&&s[q[tt]]>=s[i])tt--;
        q[++tt]=i;
    }
    printf("%lld", res);
    return 0;
}

おすすめ

転載: blog.csdn.net/SYaoJun/article/details/117812396