Longest Increasing Subsequence (LIS)
The Longest Increasing Subsequence (LIS) problem is a classic computer science problem that involves finding the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.
There are several algorithms to solve this problem, with dynamic programming being one of the most efficient approaches.
pseudocode:
In this implementation:
We initialize an array
dp
to store the length of the longest increasing subsequence ending at each index.We iterate through the input array
nums
, and for each element at indexi
, we iterate through the elements before it (indexesj < i
), checking ifnums[i]
is greater thannums[j]
. If it is, we update the length of the longest increasing subsequence ending at indexi
(dp[i]
) to be the maximum of its current value anddp[j] + 1
.After filling the
dp
array, we find the maximum value in it, which represents the length of the longest increasing subsequence in the entire array.Finally, we return the maximum length found.
This algorithm has a time complexity of O(n^2), where n is the length of the input array nums
.
There are more efficient algorithms like the Patience Sorting algorithm or using binary search to reduce the time complexity to O(n log n), but the dynamic programming approach is easier to understand and implement.
Last updated