Find the longest upstream sequence in an array (Python)

You are given an array of numbers, say

nums = [2, 5, 3, 3, 4, 6]

And I want to get the maximum possible sequence of numbers that increase, although they do not necessarily follow, while maintaining their order.

So the longest array of numbers, where A n<A <sub> n + 1sub>. In this case:

[2, 3, 4, 6]

I did this with recursion and loops, checking every possibility. This, however, takes too much time for large arrays and so my question is whether there is a better / faster way for this.

Thanks in advance!

Here is my previous code that returned the length of the final array

def bestLine(arr):
    maximum = 0
    for i in range(0, len(arr)):
        if (len(arr)-i < maximum):
            break
        maximum = max(maximum, f(i, len(arr), arr))
    return maximum

def f(start, end, arr):
    best = 0
    for i in range(start+1, end):
        if (end-i < best):
            break
        if (arr[i] > arr[start]):
            best = max(best, f(i, end, arr))
    return 1 + best
+4
source share
1 answer

My decision:

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))
0

Source: https://habr.com/ru/post/1687490/


All Articles