Apr 3, 2022

Longest increasing subsequence

 #include <iostream>

#include <cstring>

using namespace std;


int max(int a, int b) { return a>b?a:b; }

void longestIncreasingSubsequence(int a[], int n)

{

    int l[n];

    for(int i=0;i<n;i++) 

        l[i] = 1;


    for(int j=1, i=0; j<n; j++)

    {

        while(i<j)

        {

            if(a[i] < a[j])

            {

                l[j] = max(l[j], 1+l[i]);

                cout << "l[j]=" << l[j] << endl;

            }

            i++;

        }

        i=0;

    }

    

    cout<< "length of longest increasing subsequence is " << l[n-1] ;

}


int main() {

// your code goes here

int a[] = {3, 4, -1, 0, 6, 2, 3};

longestIncreasingSubsequence(a, sizeof(a)/sizeof(a[0]));

return 0;

}


Output:
l[j]=2
l[j]=2
l[j]=2
l[j]=3
l[j]=3
l[j]=3
l[j]=2
l[j]=3
l[j]=2
l[j]=3
l[j]=4
length of longest increasing subsequence is 4

No comments: