Wednesday, 26 October 2016

The Longest Increasing Subsequence

Hi Guys,How are you doing? I have a wonderful news, I tried to solve one of the Dynamic Problem
The Longest Increasing Subsequence. And the wonderful thing about this is that I have solved it in O(n log n) time , yes you heard it right! better than the Dynamic Programming approach which took O(n^2).  I have implemented the concept of PATIENCE SORTING . So What are you waiting for ?get yourself equipped with the best approach to solve Longest Increasing Sub sequence.

Following is the C++ code of the Problem:

#include<iostream>
#include<vector>
#include<algorithm>;

using namespace std;
int main(){
    vector<int>a={7,2,8,1,3,4,10,6,9,5};
    int sz = a.size();
    vector<int> b(sz, 0);
    vector<int> c(sz,0);
    c[0]=1;
    b[0]=a[0];
    for(auto i = 1;i!=a.size();++i){
        for(auto j=0;j<b.size();++j)
        if (a.at(i)>=b.at(j)){
            b[j]=a[i];
            c[j]=c[j]+1;
            break;
        }
    }
    cout<< *(max_element(c.begin(), c.end()));
}
Note: The above given algorithm may give erroneous results if you use consecutive equal values in the sequence. So, do avoid it, Or the best way is to optimize the code and Notify me in the comments below. Wishing you  "Ever Increasing Sequence of Happiness!"

No comments:

Post a Comment