Uncrossed Lines

Write the integers of nums1 and nums2 on two separate horizontal lines, in order. You may draw a straight connecting line between nums1[i] and nums2[j] when nums1[i] == nums2[j], as long as it does not cross or touch any other connecting line (each number can be used by at most one line). Return the maximum number of connecting lines you can draw.

30:00

Uncrossed Lines
medium
Free written solution
Topics
Companies

Write the integers of nums1 and nums2 on two separate horizontal lines, in order. You may draw a straight connecting line between nums1[i] and nums2[j] when nums1[i] == nums2[j], as long as it does not cross or touch any other connecting line (each number can be used by at most one line). Return the maximum number of connecting lines you can draw.

Example 1:
Input: {"nums1":[1,4,2],"nums2":[1,2,4]}
Output: 2
Constraints:
  • 1≤nums1.length,nums2.length≤5001 \leq \text{nums1.length}, \text{nums2.length} \leq 500

  • 1≤nums1[i],nums2[j]≤20001 \leq \text{nums1}[i], \text{nums2}[j] \leq 2000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums1":[1,4,2],"nums2":[1,2,4]}

dp[i][j] = most lines using the first i numbers on top and the first j on the bottom. Row 0 and column 0 are 0: an empty side allows no lines.

nums1 (first 0 in play)

lines = 0

1

4

2

1

2

4

nums2 (first 0 in play)

orange = one best set of lines for the current prefixes; dashed = pair being compared

dp[i][j]: rows = top prefix, columns = bottom prefix

·
1
2
4
·
0
0
0
0
1
0
4
0
2
0
Variables
VariableValue
m3
n3
DepthFunction Call
Stack empty
0/13