[LeetCode] Uncrossed Lines

1035. Uncrossed Lines

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int dp[500][500];
int dfs(unordered_map<int,vector<int>>& um1, unordered_map<int,vector<int>>& um2, vector<int>& n1, vector<int>& n2, int i, int j) {
if(i == n1.size() or j == n2.size()) return 0;
if(dp[i][j] != -1) return dp[i][j];
dp[i][j] = 0;
auto um2it = lower_bound(um2[n1[i]].begin(),um2[n1[i]].end(), j);
if(um2it != um2[n1[i]].end()) {
dp[i][j] = max(dp[i][j], dfs(um1, um2, n1, n2, i + 1, *um2it + 1) + 1);
}

auto um1it = lower_bound(um1[n2[j]].begin(), um1[n2[j]].end(), i);
if(um1it != um1[n2[j]].end()) {
dp[i][j] = max(dp[i][j], dfs(um1, um2, n1, n2, *um1it + 1, j + 1) + 1);
}

return dp[i][j] = max(dp[i][j], dfs(um1, um2, n1,n2,i+1,j+1));
}
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
memset(dp, -1, sizeof(dp));
unordered_map<int,vector<int>> n1, n2;
for(int i = 0; i < nums1.size(); i++) n1[nums1[i]].push_back(i);
for(int i = 0; i < nums2.size(); i++) n2[nums2[i]].push_back(i);
return dfs(n1,n2,nums1,nums2,0,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/30/PS/LeetCode/uncrossed-lines/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.