Longest Common Increasing Subsequence (LCS + LIS)

Given two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may exist)

Suppose we consider two arrays – arr1[] = {3, 4, 9, 1} and arr2[] = {5, 3, 8, 9, 10, 2, 1}

Our answer would be {3, 9} as this is the longest common subsequence which is increasing also.

public class solution {
    public int LCIS(int arr1[], int n, int arr2[], int m) {
        // dp[i] -> length of longest common increasing subsequence upto ith index
        int[] dp = new int[m];
        // Traverse all elements of arr1[]
        for (int i = 0; i < n; i++) {
            // Initialize current length of LCIS
            int current = 0;
            // For each element of arr1[], trvarse
            // all elements of arr2[].
            for (int j = 0; j < m; j++) {
                // If both the array have same elements.
                if (arr1[i] == arr2[j])
                    if (current + 1 > dp[j])
                        dp[j] = current + 1;
                // Now seek for previous smaller common element for current element of arr1
                if (arr1[i] > arr2[j])
                    if (dp[j] > current)
                        current = dp[j];
            }
        }
        int result = 0;
        for (int i = 0; i < m; i++)
            result = Math.max(result, dp[i]);
        return result;
    }
}

Last updated