Skip to content

Commit 1a73d2d

Browse files
Update longest_increasing_subsequence.py
1 parent aebba8c commit 1a73d2d

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

dynamic_programming/longest_increasing_subsequence.py

+17-9
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,25 @@ def longest_subsequence(array: list[int]) -> list[int]: # This function is recu
4242
return array
4343
# Else
4444
pivot = array[0]
45+
is_found = False
46+
i = 1
47+
longest_subseq: list[int] = []
48+
while not is_found and i < array_length:
49+
if array[i] < pivot:
50+
is_found = True
51+
temp_array = [element for element in array[i:]]
52+
temp_array = longest_subsequence(temp_array)
53+
if len(temp_array) > len(longest_subseq):
54+
longest_subseq = temp_array
55+
else:
56+
i += 1
4557

46-
# Either the subsequence contains the pivot or it does not,
47-
# The longest subsequence is calculated in both cases and
48-
# The longer subsequence is returned
49-
without_pivot = longest_subsequence(array[1:])
50-
with_pivot = [element for element in array[1:] if element >= pivot]
51-
with_pivot = [pivot, *longest_subsequence(with_pivot)]
52-
if len(with_pivot) > len(without_pivot):
53-
return with_pivot
58+
temp_array = [element for element in array[1:] if element >= pivot]
59+
temp_array = [pivot, *longest_subsequence(temp_array)]
60+
if len(temp_array) > len(longest_subseq):
61+
return temp_array
5462
else:
55-
return without_pivot
63+
return longest_subseq
5664

5765

5866
if __name__ == "__main__":

0 commit comments

Comments
 (0)