#1035
Medium Algorithms Uncrossed lines
Array Dynamic Programming
65.1% acceptance
Feb 25, 2026
3964
63
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
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn max_uncrossed_lines(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0i32; n + 1]; m + 1];
for i in 1..=m {
for j in 1..=n {
dp[i][j] = if nums1[i-1] == nums2[j-1] {
dp[i-1][j-1] + 1
} else {
dp[i-1][j].max(dp[i][j-1])
};
}
}
dp[m][n]
}
}