Skip to content

Commit 7814b28

Browse files
Merge pull request #74 from alaouimehdi1995/master
Script Output: The entire longest increasing subsequence instead of it's length
2 parents 408c5d0 + 08cbd11 commit 7814b28

File tree

1 file changed

+41
-12
lines changed

1 file changed

+41
-12
lines changed
+41-12
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,41 @@
1-
"""
2-
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
3-
"""
4-
def LIS(arr):
5-
n= len(arr)
6-
lis = [1]*n
7-
8-
for i in range(1, n):
9-
for j in range(0, i):
10-
if arr[i] > arr[j] and lis[i] <= lis[j]:
11-
lis[i] = lis[j] + 1
12-
return max(lis)
1+
'''
2+
Author : Mehdi ALAOUI
3+
4+
This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence.
5+
6+
The problem is :
7+
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
8+
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
9+
'''
10+
11+
def longestSub(ARRAY): #This function is recursive
12+
13+
ARRAY_LENGTH = len(ARRAY)
14+
if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion)
15+
return ARRAY
16+
#Else
17+
PIVOT=ARRAY[0]
18+
isFound=False
19+
i=1
20+
LONGEST_SUB=[]
21+
while(not isFound and i<ARRAY_LENGTH):
22+
if (ARRAY[i] < PIVOT):
23+
isFound=True
24+
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ]
25+
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
26+
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
27+
LONGEST_SUB = TEMPORARY_ARRAY
28+
else:
29+
i+=1
30+
31+
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ]
32+
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
33+
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
34+
return TEMPORARY_ARRAY
35+
else:
36+
return LONGEST_SUB
37+
38+
#Some examples
39+
40+
print(longestSub([4,8,7,5,1,12,2,3,9]))
41+
print(longestSub([9,8,7,6,5,7]))

0 commit comments

Comments
 (0)