思想:
i
作为某一连续区间的右端点,慢指针 j
作为该区间的左端点;t = a[1] - a[0]
,每当 a[i] - a[i - 1] == t
时更新区间,i
不断右移,直到不满足 a[i] - a[i - 1] == t
为止,此时维护最长连续区间的值 res
,t = a[i] - a[i - 1]
,再将 i --
还原,重新寻找新的差值为 t
的区间。代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 3;
int a[N];
void solve(int T){
int n; cin >> n;
for(int i = 0; i < n; i ++) cin >> a[i];
int res = 0;
int t = a[1] - a[0];
for(int i = 1, j = 0; i < n; i ++){
if(a[i] - a[i - 1] == t){
j = i; //标记左端点
while(a[i] - a[i - 1] == t && i < n) i ++; //满足相邻差值相等则 i 右移
res = max(res, i - j + 1); //更新最长的连续区间
t = a[i] - a[i - 1]; //更新为新的差值 t
i --; //还原 i,防止漏查更新后的首个区间
}
}
cout << "Case #" << T << ": " << res << endl;
}
int main(){
int _; cin >> _;
for(int i = 1; i <= _; i ++) solve(i);
return 0;
}