Skip to content

Adding LongestIncreasingSubsequence #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Python/LongestIncreasingSubsequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a
# given sequence such that all elements of the subsequence are sorted in increasing order. For example,
# 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}.

def longest_increaing_subsequence(myList):
# Initialize list with some value
lis = [1] * len(myList)
# list for storing the elements in an lis
elements = [0] * len(myList)

# Compute optimized LIS values in bottom up manner
for i in range (1 , len(myList)):
for j in range(0 , i):
if myList[i] > myList[j] and lis[i]< lis[j] + 1:
lis[i] = lis[j]+1
elements[i] = j

idx = 0

# find the maximum of the whole list and get its index in idx
maximum = max(lis) # this will give us the count of longest increasing subsequence
idx = lis.index(maximum)

# for printing the elements later
seq = [myList[idx]]
while idx != elements[idx]:
idx = elements[idx]
seq.append(myList[idx])

return (maximum, reversed(seq))

# define elements in an array
myList = [10, 22, 9, 33, 21, 50, 41, 60]
ans = longest_increaing_subsequence(myList)
print ('Length of lis is', ans[0])
print ('The longest sequence is', ', '.join(str(x) for x in ans[1]))

# OUTPUT:
# Length of lis is 5
# The longest sequence is 10, 22, 33, 50, 60