B.Arithmetic Progression
“In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant. For instance, the sequence 5, 7, 9, 11, 13, … is an arithmetic progression with common difference of 2.”
- Wikipedia
This is a quite simple problem, give you the sequence, you are supposed to find the length of the longest consecutive subsequence which is an arithmetic progression.
Input
There are several test cases. For each case there are two lines. The first line contains an integer number N (1 <= N <= 100000) indicating the number of the sequence. The following line describes the N integer numbers indicating the sequence, each number will fit in a 32bit signed integer.
Output
For each case, please output the answer in one line.
Sample Input
1 4 7 9 11 14
Sample Output
3
依题目意思,要我们求的是最长的连续等差数列,这道题目包括自己在内都以为求的是等差数列最大的公差,从而一直提交都说是超时。
下面是我给出的代码:
#include <stdio.h>
#include <stdlib.h>
#define N 100005
int p[N];
int max(int a,int b){
return (a > b ? a : b);
}
int main()
{
int n;
while(scanf("%d", &n) == 1) {
for(int i = 0; i < n; i++) {
scanf("%d", &p[i]);
}
int ans = 1, s = 0, t, d;
while(s < n - 1) {
t = s + 1, d = p[t] - p[s];
while(t < n && p[t] - p[t - 1] == d) t++;
t--;
ans = max(ans, t - s + 1);
s = t;
}
printf("%d\n", ans);
}
return 0;
}