序列游戏
Problem
有一个长度为
求这个最长区间的长度。
Input
第一行包括两个整数
接下来
Output
输出包括一个整数,表示去掉k种元素后,最长的权值相同的区间的长度。
Sample
Input 1
9 1
2
7
3
7
7
3
7
5
7
Output 1
4
Solution
双指针题。
对于右指针
用
代码:
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
using namespace std;
const int kmax = 1e5 + 3;
int n, k;
int a[kmax];
map<int, int> mp;
int c, res;
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1, j = 1; j <= n; j++) {
c += ++mp[a[j]] == 1; // 右指针移动
for (; c > k + 1; i++) { // 超过,移动左指针
c -= --mp[a[i]] == 0;
}
res = max(res, mp[a[j]]); // 记录答案
}
cout << res;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】