最长的循环子序列

时间:2017-04-01 21:18:56

标签: python algorithm

我有一个用于查找增长最长的子序列的代码,但我想扩展它以允许环绕。例如,对于序列(4,5,6,1,2,3),最长的循环子序列是(1,2,3,4,5,6),因为一旦我们达到3,我们可以回到开头序列(我们只能这样做一次。)有人能帮助我吗?

以下是代码:

def longest_increasing_subsequence(X):

N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
   lo = 1
   hi = L
   while lo <= hi:
       mid = (lo+hi)//2
       if (X[M[mid]] < X[i]):
           lo = mid+1
       else:
           hi = mid-1

   newL = lo
   P[i] = M[newL-1]
   M[newL] = i

   if (newL > L):
       L = newL

S = []
k = M[L]
for i in range(L-1, -1, -1):
    S.append(X[k])
    k = P[k]
return len(S[::-1])

2 个答案:

答案 0 :(得分:0)

将序列连接到自身的末尾,然后在其上运行算法。

答案 1 :(得分:0)

只需检查每个班次的函数返回值:

max_increasing=longest_increasing_subsequence(X)
for i in range(len(X)-1):
    X=X.append(X.pop(0)) #shift X by 1
    if longest_increasing_subsequence(X)>max_increasing:
         max_increasing=longest_increasing_subsequence(X)