首先如果a,b,c是等差数列,且b,c,d是等差数列,那么a,b,c,d也是等差数列。对于等比数列这个性质同样成立。所以只要对于每个i(1< i <n),判断a(i-1),a(i),a(i+1)是否为等差数列,是否为等比数列,就能扫一遍求出最长的等差数列和最长的等比数列了。复杂度O(N).
注意小数。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int main(){
int T;
scanf("%d",&T);
while(T--){
double ap;
double gp;
int n;
scanf("%d",&n);
double a,b;
int sumap = 2,sumgp = 2,ans = 2;
scanf("%lf",&a);
if(n == 1){
printf("1\n");
continue;
}
scanf("%lf",&b);
ap = b - a;
gp = b / a;
a = b;
double tmap,tmgp;
for(int i = 2; i < n; i++){
scanf("%lf",&b);
tmap = b - a;
tmgp = b / a;
if(ap == tmap)
sumap++;
else{
ans = max(ans,sumap);
sumap = 2;
ap = tmap;
}
if(gp == tmgp)
sumgp++;
else{
ans = max(ans,sumgp);
sumgp = 2;
gp = tmgp;
}
a = b;
}
ans = max(ans,sumap);
ans = max(ans,sumgp);
printf("%d\n",ans);
}
return 0;
}