Longest Increasing Subsequence
Question
What is the most efficient algorithm for finding the longest increasing subsequence in a given array of numbers?
Example 1
None
Solution
- ▭
- ▯
all//Longest Increasing Subsequence.py
def longest_increasing_subsequence(sequence):
longest_sequence = []
current_sequence = []
for i in range(len(sequence)):
if len(current_sequence) == 0 or sequence[i] > current_sequence[-1]:
current_sequence.append(sequence[i])
if i == len(sequence) - 1 and len(current_sequence) > len(longest_sequence):
longest_sequence = current_sequence
else:
if len(current_sequence) > len(longest_sequence):
longest_sequence = current_sequence
current_sequence = [sequence[i]]
return longest_sequence
#test
test_sequence = [1, 4, 10, 2, 8, 9, 3, 5, 6]
longest_increasing_subsequence(test_sequence)
# Output: [1, 2, 8, 9]
all//Longest Increasing Subsequence.py
def longest_increasing_subsequence(sequence):
longest_sequence = []
current_sequence = []
for i in range(len(sequence)):
if len(current_sequence) == 0 or sequence[i] > current_sequence[-1]:
current_sequence.append(sequence[i])
if i == len(sequence) - 1 and len(current_sequence) > len(longest_sequence):
longest_sequence = current_sequence
else:
if len(current_sequence) > len(longest_sequence):
longest_sequence = current_sequence
current_sequence = [sequence[i]]
return longest_sequence
#test
test_sequence = [1, 4, 10, 2, 8, 9, 3, 5, 6]
longest_increasing_subsequence(test_sequence)
# Output: [1, 2, 8, 9]