topic
We write the integers in A and B in the given order on two separate horizontal lines.
Now, we can draw some straight lines connecting two numbers A[i] and B[j], as long as A[i] == B[j], and the straight line we draw does not intersect with any other connecting lines (non-horizontal lines) .
Draw lines in this way and return the maximum number of lines we can draw.
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation:
We can draw two lines that do not cross, as shown in the figure above.
We cannot draw the third disjoint line because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
prompt:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
Problem-solving ideas and algorithms
Use dynamic programming
The essence of this problem is to find the longest common subsequence of two arrays
- Determine the meaning of the dp array: dp[i][j] represents the longest common subsequence of A[0,i-1],B[0,j-1]
- Initialization of dp array, dp[i][0]=0,dp[0][j]=0
- Determine the traversal order
- There are three directions to derive dp[i][j], so traverse from front to back and from top to bottom
Code
class Solution {
public int maxUncrossedLines(int[] A, int[] B) {
int [][] dp = new int[A.length+1][B.length+1];
for(int i=1;i<=A.length;i++) {
for(int j=1;j<=B.length;j++) {
if (A[i-1]==B[j-1]) {
dp[i][j]=dp[i-1][j-1]+1;
}
else {
dp[i][j]=Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[A.length][B.length];
}
}