You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
-
defLIS(arr):
5
-
n=len(arr)
6
-
lis= [1]*n
7
-
8
-
foriinrange(1, n):
9
-
forjinrange(0, i):
10
-
ifarr[i] >arr[j] andlis[i] <=lis[j]:
11
-
lis[i] =lis[j] +1
12
-
returnmax(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
+
deflongestSub(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
+
returnARRAY
16
+
#Else
17
+
PIVOT=ARRAY[0]
18
+
LONGEST_SUB=[] #This array will contains the longest increasing sub array
19
+
foriinrange(1,ARRAY_LENGTH):
20
+
if (ARRAY[i] <PIVOT): #For each element from the array (except the pivot), if the element is smaller than the pivot, it won't figure on the sub array that contains the pivot
21
+
TEMPORARY_ARRAY= [ elementforelementinARRAY[i:] ifelement>=ARRAY[i] ] #But it cas figure in an increasing sub array starting from this element
22
+
TEMPORARY_ARRAY=longestSub(TEMPORARY_ARRAY) #We calculate the longest sub array that starts from this element
23
+
if ( len(TEMPORARY_ARRAY) >len(LONGEST_SUB) ): #And we save the longest sub array that begins from an element smaller than the pivot (in LONGEST_SUB)
24
+
LONGEST_SUB=TEMPORARY_ARRAY
25
+
26
+
TEMPORARY_ARRAY= [ elementforelementinARRAY[1:] ifelement>=PIVOT ] #Then we delete these elements (smaller than the pivot) from the initial array
27
+
TEMPORARY_ARRAY= [PIVOT] +longestSub(TEMPORARY_ARRAY) #And we calculate the longest sub array containing the pivot (in TEMPORARY_ARRAY)
28
+
if ( len(TEMPORARY_ARRAY) >len(LONGEST_SUB) ): #Then we compare the longest array between TEMPORARY_ARRAY and LONGEST_SUB
0 commit comments