Arithmetic Progression解题报告

题目摘要:“In mathematics, an arithmeticprogression (AP) or arithmetic sequence is a sequence of numbers such that thedifference between the consecutive terms is constant. For instance, thesequence 5, 7, 9, 11, 13, … is an arithmetic progression with common differenceof 2.”

--Wikipedia

 

This is a quite simple problem, give youthe sequence, you are supposed to find the length of the longest consecutivesubsequence which is an arithmetic progression.

题目大意:给一串数字,算出其中最长等差数列的长度

输入输出要求

Input

There are several test cases. For each casethere are two lines. The first line contains an integer number N (1 <= N<= 100000) indicating the number of the sequence. The following line describesthe N integer numbers indicating the sequence, each number will fit in a 32bitsigned integer.

 

Output

For each case, please output the answer inone line.

输入输出样例

Sample Input

6

1 4 7 9 11 14

 

Sample Output

3

 

解题思路:以ans记录最终结果,d为公差,将数组元素一一枚举,l随着d的相等而增加,然后处理其他细节问题即可得到正确结果。

代码

#include<stdio.h>

#define maxn 100000+5

int Array[maxn];

 

int main()

{

       intN;

       while(scanf("%d",&N)==1)

       {

              intans=1;

              ints=0;

              intl,d;

              for(int i=0;i<N;i++)

                     scanf("%d",&Array[i]);

              while(s<N-1)

              {

                     l=s+1;

                     d=Array[l]-Array[l-1];

                     while(l<N&&Array[l]-Array[l-1]==d)

                            l++;

                     l--;

                     if(l-s+1>ans)

                            ans=l-s+1;

                     s=l;

              }

              printf("%d\n",ans);

       }    

       return0;

}

解题感想:最开始的想法比较笨,思路大致如下:将所有的公差用一个数组存起来,然后找出公差数组中连续相等的最大值,将其加一即为所求。以样例为例:给出的数组为{1,4,7,9,11,14},那么对应的公差数组为{3,3,2,2,3},连续相等的最大值为2,所以输出结果为3,按照这个思路交代码一直编译错误,改成上面的思路后还是编译错误。本来是用const定义maxn的,改成#define就没有编译错误,所以按照之前思路编的代码应该也是对的,可惜之前的代码直接被我删掉了,以后会注意把所有的思路代码都保存好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值