Skip to content

Commit ef736e1

Browse files
Create Uncrossed Lines.cpp
1 parent 5115781 commit ef736e1

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Uncrossed Lines.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
PROBLEM:
2+
3+
4+
5+
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
6+
7+
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
8+
9+
A[i] == B[j];
10+
The line we draw does not intersect any other connecting (non-horizontal) line.
11+
Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
12+
13+
Return the maximum number of connecting lines we can draw in this way.
14+
15+
16+
17+
Example 1:
18+
Input: A = [1,4,2], B = [1,2,4]
19+
Output: 2
20+
Explanation: We can draw 2 uncrossed lines as in the diagram.
21+
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
22+
23+
24+
Example 2:
25+
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
26+
Output: 3
27+
28+
29+
Example 3:
30+
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
31+
Output: 2
32+
33+
34+
Note:
35+
36+
1. 1 <= A.length <= 500
37+
2. 1 <= B.length <= 500
38+
3. 1 <= A[i], B[i] <= 2000
39+
40+
41+
42+
43+
SOLUTION:
44+
45+
46+
47+
class Solution {
48+
public:
49+
int maxUncrossedLines(vector<int>& A, vector<int>& B) {
50+
51+
int i,j,n,m;
52+
n = A.size();
53+
m = B.size();
54+
55+
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
56+
57+
for(i=1;i<=n;i++)
58+
{
59+
for(j=1;j<=m;j++)
60+
{
61+
if(A[i-1]==B[j-1])
62+
{
63+
dp[i][j] = 1 + dp[i-1][j-1];
64+
}
65+
else
66+
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
67+
}
68+
}
69+
70+
return dp[n][m];
71+
72+
}
73+
};

0 commit comments

Comments
 (0)