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