|  | 
|  | 1 | +# Author:  OMKAR PATHAK | 
|  | 2 | + | 
|  | 3 | +# The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a | 
|  | 4 | +# given sequence such that all elements of the subsequence are sorted in increasing order. For example, | 
|  | 5 | +# the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. | 
|  | 6 | + | 
|  | 7 | +def longest_increaing_subsequence(myList): | 
|  | 8 | +    # Initialize list with some value | 
|  | 9 | +    lis = [1] * len(myList) | 
|  | 10 | +    # list for storing the elements in an lis | 
|  | 11 | +    elements = [0] * len(myList) | 
|  | 12 | + | 
|  | 13 | +    # Compute optimized LIS values in bottom up manner | 
|  | 14 | +    for i in range (1 , len(myList)): | 
|  | 15 | +        for j in range(0 , i): | 
|  | 16 | +            if myList[i] > myList[j] and lis[i]< lis[j] + 1: | 
|  | 17 | +                lis[i] = lis[j]+1 | 
|  | 18 | +                elements[i] = j | 
|  | 19 | + | 
|  | 20 | +    idx = 0 | 
|  | 21 | + | 
|  | 22 | +    # find the maximum of the whole list and get its index in idx | 
|  | 23 | +    maximum = max(lis)              # this will give us the count of longest increasing subsequence | 
|  | 24 | +    idx = lis.index(maximum) | 
|  | 25 | + | 
|  | 26 | +    # for printing the elements later | 
|  | 27 | +    seq = [myList[idx]] | 
|  | 28 | +    while idx != elements[idx]: | 
|  | 29 | +        idx = elements[idx] | 
|  | 30 | +        seq.append(myList[idx]) | 
|  | 31 | + | 
|  | 32 | +    return (maximum, reversed(seq)) | 
|  | 33 | + | 
|  | 34 | +# define elements in an array | 
|  | 35 | +myList = [10, 22, 9, 33, 21, 50, 41, 60] | 
|  | 36 | +ans = longest_increaing_subsequence(myList) | 
|  | 37 | +print ('Length of lis is', ans[0]) | 
|  | 38 | +print ('The longest sequence is', ', '.join(str(x) for x in ans[1])) | 
|  | 39 | + | 
|  | 40 | +# OUTPUT: | 
|  | 41 | +# Length of lis is 5 | 
|  | 42 | +# The longest sequence is 10, 22, 33, 50, 60 | 
0 commit comments