Monday, May 23, 2016

Longest Increasing Sub sequence (LIS) Analysis



Brute Force Solution for LIS

#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[]={ 10, 22, 9, 33, 21, 50, 41, 60 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0)
  return 1;
 else
  return result;
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

int main() {
 printf("%d\n",lcs(8));
 return 0;
}

Here the time complexity is n!

Moving ahead, we can use memoization to optimize the solution.


#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int Mem[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   if (Mem[j] > 0)
    result = max(result,1+Mem[j]);
   else 
    result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0){
  Mem[i] = 1;
  return 1;
 }
 else{
  Mem[i] = result;
  return result;
 }
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

Here I have used Mem[] to remember the result. With this optimization, 
the complexity goes to O(N^2) 

We can also solve this problem using DP (Bottom up approach)
#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int dp[8];

int L(int n){
    int max2 = -1;
    for(int i=1;i<n;i++){
         for( int j=i-1;j>=0;j--){
            if(Arr[i] > Arr[j] && dp[i] < dp[j]+1){
                dp[i] = dp[j]+1;
            } 
             
         }
        max2 = max(max2,dp[i]);
    }
    
    return max2; 
}

int main() {
 for(int i=0;i<8;i++) dp[i] = 1;
 printf("%d\n",L(8));
 return 0;
}


No comments:

Post a Comment