Leetcode 1105 Solution

This article provides solution to leetcode question 1105 (uncrossed-lines)

https://leetcode.com/problems/uncrossed-lines

Solution

class Solution {
    public int maxUncrossedLines(int[] A, int[] B) {
        if (A.length == 0 || B.length == 0)
            return 0;

        int[][] dp = new int[A.length][B.length];
        for (int i = 0; i < A.length; i++)
            dp[i][0] = (A[i] == B[0] ? 1 : (i > 0 ? dp[i - 1][0] : 0));
        for (int j = 0; j < B.length; j++)
            dp[0][j] = (A[0] == B[j] ? 1 : (j > 0 ? dp[0][j - 1] : 0));

        for (int i = 1; i < A.length; i++)
            for (int j = 1; j < B.length; j++)
                dp[i][j] = (A[i] == B[j] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]));

        return dp[A.length - 1][B.length - 1];
    }
}