Longest Increasing Subsequence

Longest Incresing Subsequence(LIS)

Category : Dynamic Programming(DP)

Description : The Longest Increasing Subsequence (LIS) problem is to find the length of longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For Example, as shown by the picture.

More Examples

Input : arr[] = {3, 10, 2, 1, 20}
Output : Length of LIS = 3
The longest increasing subsequence is 3, 10 ,20

Input : arr[] = {3, 2}
Output : Length of LIS = 1
The longest increasing subsequence is {3} and {2}

Input : arr[] = {50, 3, 10, 7, 40, 80}
Output : Length of LIS = 4
The longest increasing subsequence is {3, 7, 40 ,80}

Optimal Substructrue

  1. Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS

  2. Then, L(i) can be recursively written as:

    • L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]

      or

    • L(i) = 1, if no such j exists

  3. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n

Code

int lis(int arr[], int n)
{
    int *lis, i, j, max = 0;
    lis = (int *)malloc(sizeof (int ) * n);
    
    /* init */
    for(i = 0; i < n; i++)
    {
        lis[i] = 1;
    }
    
    /* Compute optimized LIS values in bottom up manner */
    for(i = 1; i < n; i++)
    {
        for(j = 0; j < i; j++)
        {
			if(arr[i] > arr[j] && lis[i] < lis[j] + 1)
                lis[i] = lis[j] + 1;
        }
    }
    for (i = 0; i < n; i++)
    {
        if (max < lis[i])
            max = lis[i];
    }
    
    free(lis);
    
    return max;
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("Length of lis is %dn", lis( arr, n ) );
    return 0;
}
posted @ 2018-03-01 11:11  一棵球和一枝猪  阅读(183)  评论(0编辑  收藏