LeetCode1035 Uncrossed Lines
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
connecting every pair of A[i] and B[j], which A[i] == B[j]. and the line we draw does not intersect any other connecting (non-horizontal) line.
Return the maximum number of connecting lines we can draw in this way.

if you keep thinking about this peoblem, you will find out that this problem is actually the longest common subsequence. when I say “actually”, I mean iteraly. couldn’t be more classicer.
public int maxUncrossedLines(int[] A, int[] B) {
int m = A.length, n = B.length, dp[][] = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i)
for (int j = 1; j <= n; ++j)
if (A[i - 1] == B[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
return dp[m][n];
}
and of course the time complexity can be shrinked to O(n).

浙公网安备 33010602011771号