Uncrossed Lines

Medium Topics Company Tags

Place the elements of nums1 and nums2, in their given order, on two horizontal rows. You may connect equal values across the rows. Each element may be used at most once, and connecting lines must not cross. Equivalently, if two chosen pairs have first-array indices i < k, their second-array indices must satisfy j < l. Return the maximum number of connections. The arrays may have different lengths.

Example 1:

Uncrossed Lines, example 1: illustration of the example

Input: nums1 = [1,2]
nums2 = [2,1]

Output: 1

Explanation: Connecting both matching values would cross the lines because their orders differ. Connect either the two 1s or the two 2s, for one line.

Example 2:

Uncrossed Lines, example 2: illustration of the example

Input: nums1 = [5,5,5]
nums2 = [5,5]

Output: 2

Explanation: Connect the first two 5s in nums1 to the two 5s in nums2, in order. Only two elements are available in nums2, so a third line is impossible.

Example 3:

Uncrossed Lines, example 3: illustration of the example

Input: nums1 = [1,2]
nums2 = [3,4]

Output: 0

Explanation: The arrays share no value, so no connection is allowed.

Constraints:

  • 1 <= nums1.length, nums2.length <= 500
  • 1 <= nums1[i], nums2[j] <= 2000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.