扫描数组,维护当前相邻相等连续段长度,取最大值。
OJ: roj
题目 ID: 1116
难度:入门
标签:线性扫描迭代器Python
创建: 2026-09-29 19:38
更新: 2026-10-05 02:25
题目描述
给定长度为
思路
从左到右扫描,若当前元素与前一个相等则延长当前平台,否则重新开始计数,同时用全局最大值更新答案。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 19:38
# update_at: 2026-10-04 10:22
import sys
from itertools import groupby
def longest_plateau(seq: list[int]) -> int:
"""本题要求的最长平台长度:groupby 只把「相邻且相等」的元素归入同一组。"""
return max((len(list(group)) for _, group in groupby(seq)), default=0)
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data) # 题面的 n,只用来界定数组范围
seq = [next(data) for _ in range(n)]
print(longest_plateau(seq))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 02:25
* update_at: 2026-10-05 02:25
*/
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 1000005;
ll a[MAXN]; // 输入数组
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) return 0;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
int best = 0; // 最长平台长度
int run = 0; // 以当前元素结尾的平台长度
for (int i = 1; i <= n; ++i) {
if (i > 1 && a[i] == a[i - 1]) {
run = run + 1;
} else {
run = 1;
}
if (run > best) {
best = run;
}
}
cout << best << '\n';
return 0;
}