Problem Statement: Given an array of integers, determine the longest increasing subsequence (not necesarily contiguous).
Solution #1: Below is the equation and the code for the problem,
Equations:
LIS[i] = MAX( LIS[j] ) + 1; where 0 <= j < i and A[i] > A[j]
Solution #1: Below is the equation and the code for the problem,
Equations:
LIS[i] = MAX( LIS[j] ) + 1; where 0 <= j < i and A[i] > A[j]
#define MAX(a, b) ((a)>(b))?(a):(b) int LIS[1000]; int lis(int* A, int len) { int i, j; int max; LIS[0] = 1; for(i=1; i < len; i++) { max = 0; for(j=0; j < i; j++) { if(A[i] > A[j]) max = MAX(max, LIS[j]); } printf("max: %d\n", max); LIS[i] = max + 1; } return LIS[len-1]; } int main() { int A[] = {4, 3, 9, 4 ,1 ,6}; printf("LIS: %d\n", lis(A, 6)); return 0; }
1 comment:
Hi Suchit,
Here you are considering the pointers from the second characters so if the string are different the LCS is reported as 1 but it should be 0 .
So just made a few changes and seems this code works fine.
#include
#include
#define MAX(a,b) ((a)>(b))?(a):(b)
int LCS[100][100];
int lcs(char* arr1, int len1, char* arr2, int len2)
{
int i = 0;
int j = 0;
//LCS is 0 when arr2 is NULL
for(i=0; i <= len1; i++)
LCS[i][0] = 0;
//LCS is 0 when arr1 is NULL
for(j=0; j <= len2; j++)
LCS[0][j] = 0;
for(i=1; i <= len1; i++)
{
for(j= 1; j <= len2; j++)
{
if(arr1[i - 1] == arr2[j - 1])
LCS[i][j] = LCS[i-1][j-1] + 1;
else
LCS[i][j] = MAX(LCS[i-1][j], LCS[i][j-1]);
}
printf("%c\t",arr1[i]);
}
int temp = LCS[len1][len2];
return temp;
}
int main()
{
char* arr1 = "adb";
char* arr2 = "xcv";
printf("LCS: %d\n", lcs(arr1, strlen(arr1), arr2, strlen(arr2)));
return 0;
}
Please comment
Post a Comment