1035. Uncrossed Lines

1035. Uncrossed Lines

Question

You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.

We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:

  • nums1[i] == nums2[j], and
  • the line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).

Return the maximum number of connecting lines we can draw in this way.

Solution

动态规划。

假设从两个数组中分别取0到i及0到j的最大不相交线段。

对于每种取法i与j,都可以从[i-1][j]或[i][j-1]的状态进行转移。

注意当nums1[i]与nums[j]相等时,需要从[i-1][j-1]进行状态转移并加一。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int[][] dp = new int[nums1.length+1][nums2.length+1];
int max = Integer.MIN_VALUE;
for(int i = 1; i <= nums1.length; i++){
for(int j = 1; j <= nums2.length; j++){
if(nums1[i-1] == nums2[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[nums1.length][nums2.length];
}
}
Author

Xander

Posted on

2023-05-11

Updated on

2023-05-11

Licensed under

Comments