Skip to content

Commit 56b417e

Browse files
committed
Added longest increasing subsequence implementation using dynamic programming
1 parent 1d35bfe commit 56b417e

File tree

1 file changed

+42
-0
lines changed
  • pygorithm/dynamic_programming

1 file changed

+42
-0
lines changed

pygorithm/dynamic_programming/lis.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'''
2+
Author: Omkar Pathak
3+
Created At: 25th August 2017
4+
'''
5+
6+
def longest_increasing_subsequence(_list):
7+
'''
8+
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a
9+
given sequence such that all elements of the subsequence are sorted in increasing order. For example,
10+
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}.
11+
'''
12+
# Initialize list with some value
13+
lis = [1] * len(_list)
14+
# list for storing the elements in an lis
15+
elements = [0] * len(_list)
16+
17+
# Compute optimized LIS values in bottom up manner
18+
for i in range (1 , len(_list)):
19+
for j in range(0 , i):
20+
if _list[i] > _list[j] and lis[i]< lis[j] + 1:
21+
lis[i] = lis[j]+1
22+
elements[i] = j
23+
24+
idx = 0
25+
26+
# find the maximum of the whole list and get its index in idx
27+
maximum = max(lis)
28+
idx = lis.index(maximum)
29+
30+
# for printing the elements later
31+
seq = [_list[idx]]
32+
while idx != elements[idx]:
33+
idx = elements[idx]
34+
seq.append(_list[idx])
35+
36+
return (maximum, seq[::-1])
37+
38+
def get_code():
39+
"""
40+
returns the code for the longest_increasing_subsequence function
41+
"""
42+
return inspect.getsource(longest_increasing_subsequence)

0 commit comments

Comments
 (0)