1 year ago

#76311

test-img

BCBugajski

Recover solution from dynamic programming memo table

My goal is to find the longest sub-list of a list of numbers such that each element is at most 1 away from each other, e.g., a list of [0,1,2,2,3,3] from the list [0,4,1,2,2,3,3,1]. I create the memo table as follows:

def memoizeLSS(a):
    T = {} 
    n = len(a)
    for j in range(-1, n):
        T[(n, j)] = 0 # i = n and j 
        
    for i in range(0, n+1):
        for j in range(-1, n+1):
            T[(i, j)] = 0

    for i in range(n-1, -1, -1):
        for j in range(n-1, -1, -1):
            aj = a[j] if 0 <= j < len(a) else None 
            if aj != None and abs(a[i] - a[j]) > 1:
                T[(i, j)] = T[(i + 1, j)]
            elif aj == None or abs(a[i] - a[j]) <= 1:
                T[(i, j)] = max(T[(i + 1, i)] + 1, T[(i + 1, j)])

    for i in range(n-2, -1, -1):
        T[(i, -1)] = max(T[(i+1, -1)], T[(i+1, 0)], T[(i, 0)], 0)
        
    return T

I can figure out the maximum length, however I'm having trouble reconstructing the subsequence from the memo table. I tried creating a list of paired indices where the numbers are <= 1 away from and building it up from there, but there are pairs of indices which are not part of the sub-sequence and I'm stumped on what to do from here or even if creating this list is useful:

def computeLSS(a):
    T = {} 
    Y_list = []
    # Now populate the entries for the base case 
    n = len(a)
    for j in range(-1, n):
        T[(n, j)] = 0 # i = n and j 
        
    for i in range(0, n+1):
        for j in range(-1, n+1):
            T[(i, j)] = 0

    for i in range(n-1, -1, -1):
        for j in range(n-1, -1, -1):
            aj = a[j] if 0 <= j < len(a) else None 
            if aj != None and abs(a[i] - a[j]) > 1:
                T[(i, j)] = T[(i + 1, j)]
            elif aj == None or abs(a[i] - a[j]) <= 1:
                T[(i, j)] = max(T[(i + 1, i)] + 1, T[(i + 1, j)])
                if T[(i, j)] == T[(i + 1, i)] + 1 and a[i] != a[j]:
                    Y_list.append((i, j))
                
    for i in range(n-2, -1, -1):
        T[(i, -1)] = max(T[(i+1, -1)], T[(i+1, 0)], T[(i, 0)], 0)
    
    Y_list_new = []
    for x,y in Y_list:
        if x==y:
            pass
        if (y,x) in Y_list_new:
            pass
        else:
            Y_list_new.append((x,y))
    
    print(Y_list_new)
    #print(T)
    
    return

Any help is appreciated. Thank you!

python-3.x

recursion

dynamic-programming

memoization

0 Answers

Your Answer

Accepted video resources