Pages

Search This Blog

November 27, 2012

longest increasing subsequence

# translating the code from geeksforgeeks.org
class Result:
    """
    just to be in sync with code given above
    """
   def __init__(self):
        self.length = 0
        self.last_idx = 0
    def __str__(self):
        return 'Length: ' +str(self.length)
def lis(A, n):
    max_so_far = Result()
    max_so_far.length = 1
    max_so_far.last_idx = n-1
    if n== 1:
        return max_so_far
    # recursion
    for i in xrange(n-1):
        i = i+1 # since i starts with 0
       result = lis(A, i)
        if A[result.last_idx] < A[n-1]:
            result.length = result.length + 1 
            result.last_idx =n-1
        if result.length > max_so_far.length:
            max_so_far = result
    return max_so_far
A=[100, 22, 9, 33, 21, 50,41, 60]
max_so_far = lis(A, len(A))
print max_so_far

No comments:

Post a Comment