[第一次训练]Arithmetic Progression

本文解决了一个简单的算法问题,即在一个给定序列中找到最长的连续等差子序列。通过逐个比较相邻元素的差值,确定序列是否保持等差性质,从而计算并输出最长子序列的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ArithmetiProgression

“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

6

1 4 7 9 11 14

Sample Output

3



解题报告


此题已经无话可说,当时考虑太复杂了。我的理解为,当为1一个数时就是1,2个数就是2,超过两个数至少是2,然后算出后一个差值是否和前一个差值相等,相等则长度加一,不相等即可记录这个长度,待最后比较完成后,找出最长的那段即可。代码如下:

#include<stdio.h>
long long a[100010],ans[1000];
int main()
{
    long long b,x,y,m,l,c,rec;
    int i;
    while(scanf("%lld",&b)!=EOF)
    {
        for(i=0;i<b;i++)
            scanf("%d",&a[i]);
        if(b==1||b==2)
            printf("%lld\n",b);
        else
        {
            m=2;l=0;c=0;
            for(i=0;i<b-2;i++)
            {
                x=a[i+1]-a[i];
                y=a[i+2]-a[i+1];
                if(x==y)
                {
                    m++;
                    l=x;
                }
                else
                {
                    ans[c]=m;
                    m=2;
                    c++;
                }
                ans[c]=m;
            }
            rec=ans[0];
            for(i=1;i<c;i++)
            {
                if(ans[i]>rec)
                    rec=ans[i];
            }
            printf("%lld\n",rec);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值