@@ -25,7 +25,7 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
25
25
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
26
26
[1, 2, 3, 9]
27
27
>>> longest_subsequence([9, 8, 7, 6, 5, 7])
28
- [8 ]
28
+ [5, 7 ]
29
29
>>> longest_subsequence([1, 1, 1])
30
30
[1, 1, 1]
31
31
>>> longest_subsequence([])
@@ -38,25 +38,16 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
38
38
return array
39
39
# Else
40
40
pivot = array [0 ]
41
- is_found = False
42
- i = 1
43
- longest_subseq : list [int ] = []
44
- while not is_found and i < array_length :
45
- if array [i ] < pivot :
46
- is_found = True
47
- temp_array = [element for element in array [i :] if element >= array [i ]]
48
- temp_array = longest_subsequence (temp_array )
49
- if len (temp_array ) > len (longest_subseq ):
50
- longest_subseq = temp_array
51
- else :
52
- i += 1
53
41
54
- temp_array = [element for element in array [1 :] if element >= pivot ]
55
- temp_array = [pivot , * longest_subsequence (temp_array )]
56
- if len (temp_array ) > len (longest_subseq ):
57
- return temp_array
42
+ #Either the subsequence contains the pivot or it doesnt
43
+ #The sub_sequence which is longer will be returned
44
+ without_pivot = longest_subsequence (array [1 :])
45
+ with_pivot = [element for element in array [1 :] if element >= pivot ]
46
+ with_pivot = [pivot , * longest_subsequence (with_pivot )]
47
+ if len (with_pivot ) > len (without_pivot ):
48
+ return with_pivot
58
49
else :
59
- return longest_subseq
50
+ return without_pivot
60
51
61
52
62
53
if __name__ == "__main__" :
0 commit comments