The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence’s elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous or unique.

For example, the longest increasing subsequence is [0, 2, 6, 9, 11, 15] in the following subsequence:

[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]

 
This subsequence has length 6; the input sequence has no 7–member increasing subsequences. The longest increasing subsequence in this example is not unique. For instance, [0, 4, 6, 9, 11, 15] or [0, 4, 6, 9, 13, 15] are other increasing subsequences of equal length in the same input sequence.
 

Practice this problem

 
We have discussed a dynamic programming solution to solve the longest increasing subsequence problem in the previous post. In this post, another interesting DP solution is discussed in which we reduce the Longest Increasing Subsequence (LIS) to the Longest Common Subsequence (LCS). Following is the complete algorithm:

  • Create a copy of the original array.
  • Sort the copy of the original array.
  • Remove all the duplicates from the copy.
  • Perform LCS of original sequence with its modified copy.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The length of the LIS is 6

Java


Download  Run Code

Output:

The length of the LIS is 6

Python


Download  Run Code

Output:

The length of the LIS is 6

How to read out an LIS?

The idea is to read the LCS lookup table and follow the path from the bottom-right to the top-left corner of the table. If the current element in X and Y are equal, they are part of the LIS, and we move diagonally. If the current element in X and Y are different, we go up or left, depending on which cell has a higher number.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

The LIS is 0 2 6 9 11 15

Java


Download  Run Code

Output:

The LIS is 0 2 6 9 11 15

Python


Download  Run Code

Output:

The LIS is 0 2 6 9 11 15

The time complexity of the above solution is O(n2) and requires O(n2) extra space, where n is the size of the given sequence.