最大子序和(算法竞赛进阶指南 P53,单调队列)

本文详细解析了一道经典算法题“最大子序和”的解题思路与代码实现,利用单调队列解决长度不超过m的最大子序列和问题,提供了一个高效算法模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.题目链接:

最大子序和

二.题目大意:

给出长度为 n 的序列,求长度不超过 m 的最大子序和.

三.分析:

单调队列模板题

ps:这里 q[] 存的是开区间左端点

大佬的博客:单调队列学习

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long int
using namespace std;

const int M = (int)3e5;
const ll mod = (ll)1e9 + 7;
const int inf = 0x3f3f3f3f;

int q[M + 5];
int sum[M + 5];

/**
6 4
1 -3 5 1 -2 3
**/

int main()
{
    int n, m, x;
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d", &x);
        sum[i] = sum[i - 1] + x;
    }
    int l = 1;
    int r = 1;
    q[1] = 0;
    int ans = -inf;
    for(int i = 1; i <= n; ++i)
    {
        while(l <= r && q[l] < i - m)
            l++;
        ans = max(ans, sum[i] - sum[q[l]]);
        while(l <= r && sum[i] <= sum[q[r]])
            r--;
        q[++r] = i;
    }
    printf("%d\n", ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值