Longest equally-spaced subsequence

前端 未结 10 1667
遥遥无期
遥遥无期 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:48

    Here is another answer, working in time O(n^2) and without any notable memory requirements beyond that of turning the list into a set.

    The idea is quite naive: like the original poster, it is greedy and just checks how far you can extend a subsequence from each pair of points --- however, checking first that we're at the start of a subsequence. In other words, from points a and b you check how far you can extend to b + (b-a), b + 2*(b-a), ... but only if a - (b-a) is not already in the set of all points. If it is, then you already saw the same subsequence.

    The trick is to convince ourselves that this simple optimization is enough to lower the complexity to O(n^2) from the original O(n^3). That's left as an exercice to the reader :-) The time is competitive with other O(n^2) solutions here.

    A = [1, 4, 5, 7, 8, 12]    # in sorted order
    Aset = set(A)
    
    lmax = 2
    for j, b in enumerate(A):
        for i in range(j):
            a = A[i]
            step = b - a
            if b + step in Aset and a - step not in Aset:
                c = b + step
                count = 3
                while c + step in Aset:
                    c += step
                    count += 1
                #print "found %d items in %d .. %d" % (count, a, c)
                if count > lmax:
                    lmax = count
    
    print lmax
    

提交回复
热议问题