Problem
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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums1.length, nums2.length <= 500
1 <= nums1[i], nums2[j] <= 2000
Solution
Method 1 – Dynamic Programming (LCS)
Intuition
This is the same as finding the length of the longest common subsequence (LCS) between nums1 and nums2.
Approach
- Use a 2D DP array where dp[i][j] is the max number of lines for nums1[:i] and nums2[:j].
- If nums1[i-1] == nums2[j-1], dp[i][j] = dp[i-1][j-1] + 1.
- Else, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n*m)
— n = len(nums1), m = len(nums2). - 🧺 Space complexity:
O(n*m)
— For the DP table.