最大子序列和-单调队列

https://www.acwing.com/problem/content/description/137/

大意:给出长度为n的数组,求长度不超过m的连续子序列的和最大是多少。

思路:

  1. 固定右端点i,查找左端点j,如果k < j < i,并且sum[k] > sum[j]的话,那sum[i]-sum[j]一定更大,并且对于大于i的位置,都会去找j而不是k。
  2. 所有用单调队列维护一个前缀和的值随着下标增大而增大的序列,并且队列的大小不超过m,利用sum[i]-sum[q[l]]不断更新最值。
  3. 单调队列维护的下标都在[i-m,i-1]内。

code


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <queue>
//#include <bits/stdc++.h>
#define ll long long
const int N = 1e6+7;
const int mod = 1e9+7;
const ll ds = 1e15;
const double eps = 1e-8;

using namespace std;

int q[N];//q存下标
ll a[N];
void solve(){
    int n,m,l = 1,r = 1;
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> a[i];
        a[i] = a[i-1]+a[i];
    }
    ll ans = -ds;
    q[l] = 0;
    for(int i = 1; i <= n; i++){
        while(l <= r && q[l] < i-m) l++;//如果q[l]再区间[i-m,i-1]区间外,则++。
        ans = max(ans,a[i]-a[q[l]]);
        while(l <= r && a[q[r]] >= a[i]) r--;//大于a[i]并且下标大于q[l]的前缀和是没有意义的
        q[++r] = i;
    }
    cout << ans << endl;
}

int main(){
    // int t;
    // cin >> t;
    // while(t--)
        solve();
    //system("pause");
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值