Sunday, November 17, 2024
Google search engine
HomeLanguagesDynamic ProgrammingConstruction of Longest Increasing Subsequence(LIS) and printing LIS sequence

Construction of Longest Increasing Subsequence(LIS) and printing LIS sequence

The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

Examples:  

Input:  [10, 22, 9, 33, 21, 50, 41, 60, 80]
Output: [10, 22, 33, 50, 60, 80] OR [10 22 33 41 60 80] or any other LIS of same length.

In the previous post, we have discussed The Longest Increasing Subsequence problem. However, the post only covered code related to the querying size of LIS, but not the construction of LIS. In this post, we will discuss how to print LIS using a similar DP solution discussed earlier.
Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that stores LIS of arr that ends with arr[i]. For example, for array [3, 2, 6, 4, 5, 1], 

L[0]: 3
L[1]: 2
L[2]: 2 6
L[3]: 2 4
L[4]: 2 4 5
L[5]: 1

Therefore, for index i, L[i] can be recursively written as – 

L[0] = {arr[O]}
L[i] = {Max(L[j])} + arr[i] 
where j < i and arr[j] < arr[i] and if there is no such j then L[i] = arr[i]

Below is the implementation of the above idea – 

C++




/* Dynamic Programming solution to construct Longest
   Increasing Subsequence */
#include <iostream>
#include <vector>
using namespace std;
 
// Utility function to print LIS
void printLIS(vector<int>& arr)
{
    for (int x : arr)
        cout << x << " ";
    cout << endl;
}
 
// Function to construct and print Longest Increasing
// Subsequence
void constructPrintLIS(int arr[], int n)
{
    // L[i] - The longest increasing sub-sequence
    // ends with arr[i]
    vector<vector<int> > L(n);
 
    // L[0] is equal to arr[0]
    L[0].push_back(arr[0]);
 
    // start from index 1
    for (int i = 1; i < n; i++)
    {
        // do for every j less than i
        for (int j = 0; j < i; j++)
        {
            /* L[i] = {Max(L[j])} + arr[i]
            where j < i and arr[j] < arr[i] */
            if ((arr[i] > arr[j]) &&
                    (L[i].size() < L[j].size() + 1))
                L[i] = L[j];
        }
 
        // L[i] ends with arr[i]
        L[i].push_back(arr[i]);
    }
 
    // L[i] now stores increasing sub-sequence of
    // arr[0..i] that ends with arr[i]
    vector<int> max = L[0];
 
    // LIS will be max of all increasing sub-
    // sequences of arr
    for (vector<int> x : L)
        if (x.size() > max.size())
            max = x;
 
    // max will contain LIS
    printLIS(max);
}
 
// Driver function
int main()
{
    int arr[] = { 3, 2, 6, 4, 5, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // construct and print LIS of arr
    constructPrintLIS(arr, n);
 
    return 0;
}


Java




// Java program for
// the above approach
 
// Dynamic Programming
// solution to construct Longest
// Increasing Subsequence
import java.util.*;
class GFG{
 
// Utility function to print LIS
static void printLIS(Vector<Integer> arr)
{
  for (int x : arr)
    System.out.print(x + " ");
  System.out.println();
}
 
// Function to construct and print
// Longest Increasing Subsequence
static void constructPrintLIS(int arr[],
                              int n)
{
  // L[i] - The longest increasing
  // sub-sequence ends with arr[i]
  Vector<Integer> L[] = new Vector[n];
  for (int i = 0; i < L.length; i++)
    L[i] = new Vector<Integer>();
   
  // L[0] is equal to arr[0]
  L[0].add(arr[0]);
 
  // Start from index 1
  for (int i = 1; i < n; i++)
  {
    // Do for every j less than i
    for (int j = 0; j < i; j++)
    {
      //L[i] = {Max(L[j])} + arr[i]
      // where j < i and arr[j] < arr[i]
      if ((arr[i] > arr[j]) &&
          (L[i].size() < L[j].size() + 1))
        L[i] = (Vector<Integer>) L[j].clone();  //deep copy
    }
 
    // L[i] ends with arr[i]
    L[i].add(arr[i]);
  }
 
  // L[i] now stores increasing sub-sequence of
  // arr[0..i] that ends with arr[i]
  Vector<Integer> max = L[0];
   
  // LIS will be max of all increasing sub-
  // sequences of arr
  for (Vector<Integer> x : L)
    if (x.size() > max.size())
      max = x;
 
  // max will contain LIS
  printLIS(max);
}
 
// Driver function
public static void main(String[] args)
{
  int arr[] = {3, 2, 4, 5, 1};
  int n = arr.length;
 
  // print LIS of arr
  constructPrintLIS(arr, n);
}
}
 
// This code is contributed by gauravrajput1


Python3




# Dynamic Programming solution to construct Longest
# Increasing Subsequence
 
# Utility function to print LIS
def printLIS(arr: list):
    for x in arr:
        print(x, end=" ")
    print()
 
# Function to construct and print Longest Increasing
# Subsequence
def constructPrintLIS(arr: list, n: int):
 
    # L[i] - The longest increasing sub-sequence
    # ends with arr[i]
    l = [[] for i in range(n)]
 
    # L[0] is equal to arr[0]
    l[0].append(arr[0])
 
    # start from index 1
    for i in range(1, n):
 
        # do for every j less than i
        for j in range(i):
 
            # L[i] = {Max(L[j])} + arr[i]
            # where j < i and arr[j] < arr[i]
            if arr[i] > arr[j] and (len(l[i]) < len(l[j]) + 1):
                l[i] = l[j].copy()
 
        # L[i] ends with arr[i]
        l[i].append(arr[i])
 
    # L[i] now stores increasing sub-sequence of
    # arr[0..i] that ends with arr[i]
    maxx = l[0]
 
    # LIS will be max of all increasing sub-
    # sequences of arr
    for x in l:
        if len(x) > len(maxx):
            maxx = x
 
    # max will contain LIS
    printLIS(maxx)
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 2, 6, 4, 5, 1]
    n = len(arr)
 
    # construct and print LIS of arr
    constructPrintLIS(arr, n)
 
# This code is contributed by
# sanjeev2552


C#




// Dynamic Programming solution to construct Longest
// Increasing Subsequence
using System;
using System.Collections.Generic;
class GFG
{
     
    // Utility function to print LIS
    static void printLIS(List<int> arr)
    {
        foreach(int x in arr)
        {
            Console.Write(x + " ");
        }
        Console.WriteLine();
    }
      
    // Function to construct and print Longest Increasing
    // Subsequence
    static void constructPrintLIS(int[] arr, int n)
    {
       
        // L[i] - The longest increasing sub-sequence
        // ends with arr[i]
        List<List<int>> L = new List<List<int>>();
        for(int i = 0; i < n; i++)
        {
            L.Add(new List<int>());
        }
      
        // L[0] is equal to arr[0]
        L[0].Add(arr[0]);
      
        // start from index 1
        for (int i = 1; i < n; i++)
        {
            // do for every j less than i
            for (int j = 0; j < i; j++)
            {
                /* L[i] = {Max(L[j])} + arr[i]
                where j < i and arr[j] < arr[i] */
                if ((arr[i] > arr[j]) && (L[i].Count < L[j].Count + 1))
                    L[i] = L[j];
            }
      
            // L[i] ends with arr[i]
            L[i].Add(arr[i]);
        }
      
        // L[i] now stores increasing sub-sequence of
        // arr[0..i] that ends with arr[i]
        List<int> max = L[0];
      
        // LIS will be max of all increasing sub-
        // sequences of arr
        foreach(List<int> x in L)
        {
            if (x.Count > max.Count)
            {
                max = x;
            }
        }
      
        // max will contain LIS
        printLIS(max);
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 3, 2, 4, 5, 1 };
    int n = arr.Length;
  
    // construct and print LIS of arr
    constructPrintLIS(arr, n);
  }
}
 
// This code is contributed by divyesh072019


Javascript




<script>
// JavaScript program Dynamic Programming solution to construct Longest
//   Increasing Subsequence
 
function printLIS( x)
{
   document.write(x+" ");
}
 
// Function to construct and print Longest Increasing
// Subsequence
function constructPrintLIS( arr,  n)
{
    // L[i] - The longest increasing sub-sequence
    // ends with arr[i]
    var L = new Array(n);
    for(var i = 0; i < n;i++){
      L[i] = [];
    }
    // L[0] is equal to arr[0]
    L[0].push(arr[0]);
 
    // start from index 1
    for (var i = 1; i < n; i++)
    {
        // do for every j less than i
        for (var j = 0; j < i; j++)
        {
            /* L[i] = {Max(L[j])} + arr[i]
            where j < i and arr[j] < arr[i] */
            if ((arr[i] > arr[j]) && (L[i].length< L[j].length + 1))
                L[i] = [...L[j]];
        }
 
        // L[i] ends with arr[i]
        L[i].push(arr[i]);
         
    }
 
    // L[i] now stores increasing sub-sequence of
    // arr[0..i] that ends with arr[i]
    var max = 0;
 
    // LIS will be max of all increasing sub-
    // sequences of arr
    for (var x=0; x < L.length;x++){
        if (L[x].length> L[max].length)
            max = x;
}
    // L[max] will contain LIS
    L[max].forEach(printLIS);
    
}
 
 
var arr = [3, 2, 6, 4, 5, 1 ];
var n = 6;
 
// construct and print LIS of arr
constructPrintLIS(arr, n);
 
</script>


Output

2 4 5 

Note that the time complexity of the above Dynamic Programming (DP) solution is O(n^3) (n^2 for two nested loops and n for copying another vector in a vector eg: L[i] = L[j] contributes O(n) also) and space complexity is O(n^2) as we are using 2d vector to store our LIS and there is a O(n Log n) non-DP solution for the LIS problem. See below post for O(n Log n) solution.

Construction of Longest Monotonically Increasing Subsequence (N log N)

This article is contributed by Aditya Goel. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments