且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找出序列中最长的等差数列

更新时间:2023-01-10 09:49:57

按照您的链接并运行第二个示例,看起来代码实际上找到了合适的 LAP

Following your link and running second sample, it looks like the code actually find proper LAP

5, 10, 15, 20, 25, 30,

5, 10, 15, 20, 25, 30,

但未能找到合适的长度.我没有花太多时间分析代码而是分析代码

but fails to find proper length. I didn't spend too much time analyzing the code but the piece

    // Any 2-letter series is an AP
    // Here we initialize only for the last column of lookup because
    // all i and (n-1) pairs form an AP of size 2  
    for (int i=0; i<n; i++)
        lookup[i][n-1] = 2;

对我来说看起来很可疑.似乎您需要用 2 而不是最后一列来初始化 whole lookup 表,如果我这样做,它也会开始在您的样本上获得正确的长度.

looks suspicious to me. It seems that you need to initialize whole lookup table with 2 instead of just last column and if I do so, it starts to get correct length on your sample as well.

因此摆脱初始化"循环并将第三行更改为以下代码:

So get rid of the "initialise" loop and change your 3rd line to following code:

# initialise whole table with 2 as all (i, j) pairs have length 2    
Table = [[2 for _ in range(n)] for _ in range(n)]

此外他们的

示例执行:
最大 AP 长度 = 6
3, 5, 7, 9, 11, 13, 15, 17,

Sample Execution:
Max AP length = 6
3, 5, 7, 9, 11, 13, 15, 17,

也包含此错误,并且仅由于运气而实际打印正确的序列.如果我将 sortedArr 修改为

Contains this bug as well and actually prints correct sequence only because of sheer luck. If I modify the sortedArr to

int sortedArr[] = new int[] {3, 4, 5, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18,  112, 113, 114, 115, 116, 117, 118};

我得到以下输出

最大 AP 长度 = 7
112, 113, 114, 115, 116, 117, 118,

Max AP length = 7
112, 113, 114, 115, 116, 117, 118,

这显然是错误的,因为原来的 8 项长序列 3,5,7,9,11,13,15,17, 仍然存在.

which is obviously wrong as original 8-items long sequence 3, 5, 7, 9, 11, 13, 15, 17, is still there.