Skip to content

Commit

Permalink
Code optimized and complexity decreased
Browse files Browse the repository at this point in the history
  • Loading branch information
alaouimehdi1995 committed Apr 10, 2017
1 parent e01cf42 commit 08cbd11
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,24 @@ def longestSub(ARRAY): #This function is recursive
return ARRAY
#Else
PIVOT=ARRAY[0]
LONGEST_SUB=[] #This array will contains the longest increasing sub array
for i in range(1,ARRAY_LENGTH): #For each element from the array (except the pivot),
if (ARRAY[i] < PIVOT): #if the element is smaller than the pivot, it won't figure on the sub array that contains the pivot
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ] #But it cas figure in an increasing sub array starting from this element
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY) #We calculate the longest sub array that starts from this element
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)
isFound=False
i=1
LONGEST_SUB=[]
while(not isFound and i<ARRAY_LENGTH):
if (ARRAY[i] < PIVOT):
isFound=True
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ]
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
LONGEST_SUB = TEMPORARY_ARRAY
else:
i+=1

TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ] #Then we delete these elements (smaller than the pivot) from the initial array
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY) #And we calculate the longest sub array containing the pivot (in TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ): #Then we compare the longest array between TEMPORARY_ARRAY and LONGEST_SUB
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ]
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
return TEMPORARY_ARRAY
else: #And we return the longest one
else:
return LONGEST_SUB

#Some examples
Expand Down

0 comments on commit 08cbd11

Please sign in to comment.