Longest equally-spaced subsequence

前端 未结 10 1682
遥遥无期
遥遥无期 2020-12-22 19:12

I have a million integers in sorted order and I would like to find the longest subsequence where the difference between consecutive pairs is equal. For example



        
10条回答
  •  醉酒成梦
    2020-12-22 19:52

    UPDATE: I've found a paper on this problem, you can download it here.

    Here is a solution based on dynamic programming. It requires O(n^2) time complexity and O(n^2) space complexity, and does not use hashing.

    We assume all numbers are saved in array a in ascending order, and n saves its length. 2D array l[i][j] defines length of longest equally-spaced subsequence ending with a[i] and a[j], and l[j][k] = l[i][j] + 1 if a[j] - a[i] = a[k] - a[j] (i < j < k).

    lmax = 2
    l = [[2 for i in xrange(n)] for j in xrange(n)]
    for mid in xrange(n - 1):
        prev = mid - 1
        succ = mid + 1
        while (prev >= 0 and succ < n):
            if a[prev] + a[succ] < a[mid] * 2:
                succ += 1
            elif a[prev] + a[succ] > a[mid] * 2:
                prev -= 1
            else:
                l[mid][succ] = l[prev][mid] + 1
                lmax = max(lmax, l[mid][succ])
                prev -= 1
                succ += 1
    
    print lmax
    

提交回复
热议问题