B.Arithmetic Progression
“Inmathematics, an arithmetic progression (AP) or arithmetic sequence is asequence of numbers such that the difference between the consecutive terms isconstant. For instance, the sequence 5, 7, 9, 11, 13, … is an arithmeticprogression with common difference of 2.”
- Wikipedia
Thisis a quite simple problem, give you the sequence, you are supposed to find thelength of the longest consecutive subsequence which is an arithmeticprogression.
Input
Thereare several test cases. For each case there are two lines. The first linecontains an integer number N (1 <= N <= 100000) indicating the number ofthe sequence. The following line describes the N integer numbers indicating thesequence, each number will fit in a 32bit signed integer.
Output
Foreach case, please output the answer in one line.
Sample Input
1 4 7 9 11 14
Sample Output
3
---------------------------------------------------------------------------------------------
解题报告:个人想法就是:
1)一个个数据输入时,记录上一个数(a)与现在输入的数(b);
2)比较二者差值(b-a),满足上一个等差(dis)的,长度(count)+1;
3)不满足的,(与最大长度(max)比较后)长度重新初始化,重新记录;
4)输出最大长度(max)。
代码:
#include<stdio.h>
int main()
{
int n,i,j,a,b,count,max,dis;
//输入整数数 i,j 前一个 后一个 等差总数 最长值 等差差值
while( EOF != scanf("%d",&n) )
{
if(1==n) //只有一个数时
{
scanf("%d",&a);
printf("1\n");
}
else
{
scanf("%d%d",&a,&b);//存入第一二个
dis=b-a; //初始化 等差
max=count=2; //初始化 长度
for(i=2;i<n;i++)
{
a=b; //更改 前一个值
scanf("%d",&b);//存入 后一个值
if( b-a==dis) count++; //满足 上一次 等差? ++
else //不满足 时
{
if( max<count )max=count;//记录 最长长度
dis=b-a; //重新 确定 新的 等差
count=2; //重新 初始化 长度
}
}
if( max<count )max=count;//都满足 上一次等差 记录最长长度
printf("%d\n",max);
}
}
return 0;
}