Skip to content

Commit 08cbd11

Browse files
Code optimized and complexity decreased
1 parent e01cf42 commit 08cbd11

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

Diff for: dynamic_programming/longest_increasing_subsequence.py

+15-10
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,24 @@ def longestSub(ARRAY): #This function is recursive
1515
return ARRAY
1616
#Else
1717
PIVOT=ARRAY[0]
18-
LONGEST_SUB=[] #This array will contains the longest increasing sub array
19-
for i in range(1,ARRAY_LENGTH): #For each element from the array (except the pivot),
20-
if (ARRAY[i] < PIVOT): #if the element is smaller than the pivot, it won't figure on the sub array that contains the pivot
21-
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
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)
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) ):
2427
LONGEST_SUB = TEMPORARY_ARRAY
28+
else:
29+
i+=1
2530

26-
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= 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
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) ):
2934
return TEMPORARY_ARRAY
30-
else: #And we return the longest one
35+
else:
3136
return LONGEST_SUB
3237

3338
#Some examples

0 commit comments

Comments
 (0)