我的解决方案
def best_sequence_length(arr):
'''Find length of the longest ascending sequence in an array'''
arr_length = len(arr)
if arr_length <= 1:
return arr_length
longest = [1] # will store the lengths of the longest sequence ending on this index
best_idx_at_all = 0
for idx in range(1,arr_length):
best_len_so_far = 1
back = -1
for i in range(len(longest)+1):
if arr[i] < arr[idx] and best_len_so_far <= longest[i]:
best_len_so_far = longest[i] + 1
back = i
longest.append(longest[back]+1 if back > -1 else 1)
if longest[best_idx_at_all] < longest[idx]:
best_idx_at_all = idx
return longest[best_idx_at_all]
这可能不是非常“pythonic”(它类似于C或甚至FORTRAN代码:-),但它具有O(n ^ 2)复杂度.
如果你想获得最长的序列,而不仅仅是它的长度(可能是模糊的),上面的函数只需要稍加修改:
def best_sequence(arr):
'''Find longest ascending sequence in an array'''
arr_length = len(arr)
if arr_length <= 1:
return arr
longest = [1] # will store the length of the longest sequence ending on this index
back_link = [-1] # link to the previous element in the longest sequence or -1
best_idx_at_all = 0
for idx in range(1,arr_length):
best_len_so_far = 1
back = -1
for i in range(len(longest)+1):
if arr[i] < arr[idx] and best_len_so_far <= longest[i]:
best_len_so_far = longest[i] + 1
back = i
back_link.append(back)
longest.append(longest[back]+1 if back > -1 else 1)
if longest[best_idx_at_all] < longest[idx]:
best_idx_at_all = idx
nxt = best_idx_at_all
result = []
while nxt >= 0:
result.append(arr[nxt])
nxt = back_link[nxt]
return list(reversed(result))