From 08cbd113a4a4aa87ee1bc278ff19791806763492 Mon Sep 17 00:00:00 2001 From: Mehdi ALAOUI Date: Mon, 10 Apr 2017 13:49:01 +0100 Subject: [PATCH] Code optimized and complexity decreased --- .../longest_increasing_subsequence.py | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/dynamic_programming/longest_increasing_subsequence.py b/dynamic_programming/longest_increasing_subsequence.py index e3f0a668b..c04f6673f 100644 --- a/dynamic_programming/longest_increasing_subsequence.py +++ b/dynamic_programming/longest_increasing_subsequence.py @@ -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[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