DDSA Solutions

Longest Common Increasing Subsequence

Time: O(n*m)
Space: O(m)
Advertisement

Intuition

Combine LCS and LIS. dp[j] = length of LCIS ending with B[j]. For each A[i], update dp[j] for B[j]==A[i] using best candidate from previous elements.

Algorithm

  1. 1For each i (A): best = 0. For each j (B):
  2. 2If A[i] == B[j]: dp[j] = best + 1.
  3. 3If A[i] > B[j]: best = max(best, dp[j]).
  4. 4Return max(dp).

Common Pitfalls

  • Track "best" separately to avoid using updated dp values in same outer iteration.
Longest Common Increasing Subsequence.java
Java
// Approach: DP combining LCS and LIS. dp[j] = length of LCIS ending at B[j].
// Time: O(n*m) Space: O(m)
class Solution {
    public int LCIS(int[] a, int[] b) {
        int n = a.length, m = b.length;
        int[] dp = new int[m];
        for (int i = 0; i < n; i++) {
            int currentMax = 0;
            for (int j = 0; j < m; j++) {
                if (a[i] == b[j])
                    dp[j] = currentMax + 1;
                else if (b[j] < a[i])
                    currentMax = Math.max(currentMax, dp[j]);
            }
        }
        
        int ans = 0;
        for (int v : dp)
            ans = Math.max(ans, v);

        return ans;
    }
}
Advertisement
Was this solution helpful?