Skip to content

Commit 74e269b

Browse files
authored
Fix #12510
1 parent bae33ac commit 74e269b

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

dynamic_programming/longest_increasing_subsequence.py

+9-18
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
2525
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
2626
[1, 2, 3, 9]
2727
>>> longest_subsequence([9, 8, 7, 6, 5, 7])
28-
[8]
28+
[5, 7]
2929
>>> longest_subsequence([1, 1, 1])
3030
[1, 1, 1]
3131
>>> longest_subsequence([])
@@ -38,25 +38,16 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
3838
return array
3939
# Else
4040
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
5341

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
5849
else:
59-
return longest_subseq
50+
return without_pivot
6051

6152

6253
if __name__ == "__main__":

0 commit comments

Comments
 (0)