题目来源:码蹄集
题目描述:
C++代码实现:
参考链接:https://yxsmarter.blog.csdn.net/article/details/128221092?spm=1001.2014.3001.5502
#include<bits/stdc++.h>
#define oo 0x3f3f3f3f
#define OO 0x3f3f3f3f3f3f3f3f
#define LL long long
#define all(x) x.begin(),x.end()
#define close() ios::sync_with_stdio(0),cin.tie(nullptr),cout.tie(nullptr)
using namespace std;
const int N=1e5;
int main(){
int n,ans=0;
cin>>n;
vector<int> a(n) , f(N+1) ;
for(auto &x:a) cin>>x;//建议的读入写法
f[a[0]]=f[a[0]-1]=ans=1;//初始化
for(int i=1;i<n;++i){//主要部分
if(a[i-1]!=a[i]){
if(a[i-1]!=a[i]-1) f[a[i]-1]=0;
if(a[i-1]!=a[i]+1) f[a[i]]=0;
}
f[a[i]]+=1,f[a[i]-1]+=1;
ans=max(ans,max(f[a[i]],f[a[i]-1]));
}
cout<<ans<<'\n';
return 0;
}
Python代码实现:
import sys
input = sys.stdin.readline
N = 100001
n = int(input())
a = list(map(int, input().split()))
f = [0] * N
f[a[0]] = f[a[0]-1] = ans = 1
for i in range(1,n):
if a[i-1] != a[i]:
if a[i-1] != a[i]-1:
f[a[i]-1] = 0
if a[i-1] != a[i]+1:
f[a[i]] = 0
f[a[i]] += 1
f[a[i]-1] += 1
ans = max(ans, max(f[a[i]], f[a[i]-1]))
print(ans)
Java代码实现:
import java.io.*;
import java.util.*;
public class Main {
static int oo = 0x3f3f3f3f;
static long OO = 0x3f3f3f3f3f3f3f3fL;
static long MOD = 998244353L;
static int N = 100001;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(st.nextToken());
}
int ans = 0;
int[] f = new int[N+1];
f[a[0]] = f[a[0]-1] = ans = 1;
for(int i=1; i<n; i++){
if(a[i-1] != a[i]){
if(a[i-1] != a[i]-1) f[a[i]-1] = 0;
if(a[i-1] != a[i]+1) f[a[i]] = 0;
}
f[a[i]] += 1;
f[a[i]-1] += 1;
ans = Math.max(ans, Math.max(f[a[i]], f[a[i]-1]));
}
System.out.println(ans);
}
}
代码提交测试结果:
附B站老师思路讲解:https://www.bilibili.com/video/BV1Ds4y1m7o9/?t=2016.4&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118