// A C# program to find length of the Longest Common // Increasing Subsequence (LCIS) using memoization using System; class GfG { // Recursive function with memoization to find LCIS static int FindLCIS(int i, int j, int prevIndex, int[] a, int[] b, int[, , ] memo){ // Base case: If either array is fully traversed if (i < 0 || j < 0) return 0; // If the result has already been computed, return // it if (memo[i, j, prevIndex + 1] != -1) return memo[i, j, prevIndex + 1]; int include = 0; int exclude = 0; // If the current elements match and satisfy the // increasing condition if (a[i] == b[j] && (prevIndex == -1 || a[i] < a[prevIndex])) { // Include the current element include = 1 + FindLCIS( i - 1, j - 1, i, a, b, memo); } // Explore excluding the current element from either // array exclude = Math.Max( FindLCIS(i - 1, j, prevIndex, a, b, memo), FindLCIS(i, j - 1, prevIndex, a, b, memo)); // Store the result in the memo table and return it memo[i, j, prevIndex + 1] = Math.Max(include, exclude); return memo[i, j, prevIndex + 1]; } // Function to initialize the memo table and start the // recursion static int LCIS(int[] a, int[] b){ int m = a.Length; int n = b.Length; // Initialize the memoization table with -1 // (indicating uncomputed states) int[, , ] memo = new int[m, n, m + 1]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m + 1; k++) { memo[i, j, k] = -1; } } } // Start recursion from the last indices with no // previous element return FindLCIS(m - 1, n - 1, -1, a, b, memo); } static void Main(string[] args){ int[] a = {3, 4, 9, 1 }; int[] b = { 5, 3, 8, 9, 10, 2, 1 }; Console.WriteLine(LCIS(a, b)); } }