Arithmetic Progression超时了n次,终于过了!

来源:互联网 发布:淘宝购物退款退到哪里 编辑:程序博客网 时间:2024/04/28 07:55

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.
输入格式
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.
输出
For each case, please output the answer in one line.
样例输入
6
1 4 7 9 11 14
样例输出
3

代码:

#include<stdio.h>

#define N 100005
int a[100001];
int max(int x,int y){
return(x>y?x:y);
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF) 
{
for(i=0;i<n;i++) 
{
scanf("%d",&a[i]);
}
int m=1,j=0,k,s;
while(j<n-1) 
{
k=j+1; 
s=a[k] - a[j];
while(k<n&&(a[k]-a[k-1])==s) 
k++;
k--;
m=max(m, k-j+1);
j=k;
}
printf("%d\n",m);
}
return 0;
}