Related Articles
Maximum number of uncrossed lines between two given arrays
• Difficulty Level : Hard
• Last Updated : 18 Sep, 2020

Given two arrays A[] and B[], the task is to find the maximum number of uncrossed lines between the elements of the two given arrays.

A straight line can be drawn between two array elements A[i] and B[j] only if:

• A[i] = B[j]
• The line does not intersect any other line.

Examples:

Input: A[] = {3, 9, 2}, B[] = {3, 2, 9}
Output:
Explanation:
The lines between A[0] to B[0] and A[1] to B[2] does not intersect each other.

Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}
Output: 5

Naive Approach: The idea is to generate all the subsequences of array A[] and try to find them in array B[] so that the two subsequences can be connected by joining straight lines. The longest such subsequence found to be common in A[] and B[] would have the maximum number of uncrossed lines. So print the length of that subsequence.

Time Complexity: O(M * 2N
Auxiliary Space: O(1)

Efficient Approach: From the above approach, it can be observed that the task is to find the longest subsequence common in both the arrays. Therefore, the above approach can be optimized by finding the Longest Common Subsequence between the two arrays using Dynamic Programming.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`` ` `#include ``using` `namespace` `std;`` ` `// Function to count maximum number``// of uncrossed lines between the``// two given arrays``int` `uncrossedLines(``int``* a, ``int``* b,``                   ``int` `n, ``int` `m)``{``    ``// Stores the length of lcs``    ``// obtained upto every index``    ``int` `dp[n + 1][m + 1];`` ` `    ``// Iterate over first array``    ``for` `(``int` `i = 0; i <= n; i++) {`` ` `        ``// Iterate over second array``        ``for` `(``int` `j = 0; j <= m; j++) {`` ` `            ``if` `(i == 0 || j == 0)`` ` `                ``// Update value in dp table``                ``dp[i][j] = 0;`` ` `            ``// If both characters``            ``// are equal``            ``else` `if` `(a[i - 1] == b[j - 1])`` ` `                ``// Update the length of lcs``                ``dp[i][j] = 1 + dp[i - 1][j - 1];`` ` `            ``// If both characters``            ``// are not equal``            ``else`` ` `                ``// Update the table``                ``dp[i][j] = max(dp[i - 1][j],``                               ``dp[i][j - 1]);``        ``}``    ``}`` ` `    ``// Return the answer``    ``return` `dp[n][m];``}`` ` `// Driver Code``int` `main()``{``    ``// Given array A[] and B[]``    ``int` `A[] = { 3, 9, 2 };``    ``int` `B[] = { 3, 2, 9 };`` ` `    ``int` `N = ``sizeof``(A) / ``sizeof``(A[0]);``    ``int` `M = ``sizeof``(B) / ``sizeof``(B[0]);`` ` `    ``// Function Call``    ``cout << uncrossedLines(A, B, N, M);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;`` ` `class` `GFG{`` ` `// Function to count maximum number``// of uncrossed lines between the``// two given arrays``static` `int` `uncrossedLines(``int``[] a, ``int``[] b,``                          ``int` `n, ``int` `m)``{``     ` `    ``// Stores the length of lcs``    ``// obtained upto every index``    ``int``[][] dp = ``new` `int``[n + ``1``][m + ``1``];`` ` `    ``// Iterate over first array``    ``for``(``int` `i = ``0``; i <= n; i++) ``    ``{``         ` `        ``// Iterate over second array``        ``for``(``int` `j = ``0``; j <= m; j++) ``        ``{``            ``if` `(i == ``0` `|| j == ``0``)``             ` `                ``// Update value in dp table``                ``dp[i][j] = ``0``;`` ` `            ``// If both characters``            ``// are equal``            ``else` `if` `(a[i - ``1``] == b[j - ``1``])`` ` `                ``// Update the length of lcs``                ``dp[i][j] = ``1` `+ dp[i - ``1``][j - ``1``];`` ` `            ``// If both characters``            ``// are not equal``            ``else`` ` `                ``// Update the table``                ``dp[i][j] = Math.max(dp[i - ``1``][j],``                                    ``dp[i][j - ``1``]);``        ``}``    ``}`` ` `    ``// Return the answer``    ``return` `dp[n][m];``}`` ` `// Driver Code``public` `static` `void` `main (String[] args)``{``     ` `    ``// Given array A[] and B[]``    ``int` `A[] = { ``3``, ``9``, ``2` `};``    ``int` `B[] = { ``3``, ``2``, ``9` `};`` ` `    ``int` `N = A.length;``    ``int` `M = B.length;`` ` `    ``// Function call``    ``System.out.print(uncrossedLines(A, B, N, M));``}``}`` ` `// This code is contributed by code_hunt`

## Python3

 `# Python3 program for ``# the above approach`` ` `# Function to count maximum number``# of uncrossed lines between the``# two given arrays``def` `uncrossedLines(a, b,``                   ``n, m):`` ` `    ``# Stores the length of lcs``    ``# obtained upto every index``    ``dp ``=` `[[``0` `for` `x ``in` `range``(m ``+` `1``)]``             ``for` `y ``in` `range``(n ``+` `1``)]``  ` `    ``# Iterate over first array``    ``for` `i ``in` `range` `(n ``+` `1``):``  ` `        ``# Iterate over second array``        ``for` `j ``in` `range` `(m ``+` `1``):``  ` `            ``if` `(i ``=``=` `0` `or` `j ``=``=` `0``):``  ` `                ``# Update value in dp table``                ``dp[i][j] ``=` `0``  ` `            ``# If both characters``            ``# are equal``            ``elif` `(a[i ``-` `1``] ``=``=` `b[j ``-` `1``]):``  ` `                ``# Update the length of lcs``                ``dp[i][j] ``=` `1` `+` `dp[i ``-` `1``][j ``-` `1``]``  ` `            ``# If both characters``            ``# are not equal``            ``else``:``  ` `                ``# Update the table``                ``dp[i][j] ``=` `max``(dp[i ``-` `1``][j],``                               ``dp[i][j ``-` `1``])``  ` `    ``# Return the answer``    ``return` `dp[n][m]``  ` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``   ` `    ``# Given array A[] and B[]``    ``A ``=` `[``3``, ``9``, ``2``]``    ``B ``=` `[``3``, ``2``, ``9``]``  ` `    ``N ``=` `len``(A)``    ``M ``=` `len``(B)``  ` `    ``# Function Call``    ``print` `(uncrossedLines(A, B, N, M))`` ` `# This code is contributed by Chitranayal`

## C#

 `// C# program for the above approach``using` `System;`` ` `class` `GFG{`` ` `// Function to count maximum number``// of uncrossed lines between the``// two given arrays``static` `int` `uncrossedLines(``int``[] a, ``int``[] b,``                          ``int` `n, ``int` `m)``{``     ` `    ``// Stores the length of lcs``    ``// obtained upto every index``    ``int``[,] dp = ``new` `int``[n + 1, m + 1];`` ` `    ``// Iterate over first array``    ``for``(``int` `i = 0; i <= n; i++)``    ``{`` ` `        ``// Iterate over second array``        ``for``(``int` `j = 0; j <= m; j++) ``        ``{``            ``if` `(i == 0 || j == 0)`` ` `                ``// Update value in dp table``                ``dp[i, j] = 0;`` ` `            ``// If both characters``            ``// are equal``            ``else` `if` `(a[i - 1] == b[j - 1])`` ` `                ``// Update the length of lcs``                ``dp[i, j] = 1 + dp[i - 1, j - 1];`` ` `            ``// If both characters``            ``// are not equal``            ``else`` ` `                ``// Update the table``                ``dp[i, j] = Math.Max(dp[i - 1, j],``                                    ``dp[i, j - 1]);``        ``}``    ``}`` ` `    ``// Return the answer``    ``return` `dp[n, m];``}`` ` `// Driver Code``public` `static` `void` `Main (String[] args)``{``     ` `    ``// Given array A[] and B[]``    ``int``[] A = { 3, 9, 2 };``    ``int``[] B = { 3, 2, 9 };`` ` `    ``int` `N = A.Length;``    ``int` `M = B.Length;`` ` `    ``// Function call``    ``Console.Write(uncrossedLines(A, B, N, M));``}``}`` ` `// This code is contributed by code_hunt``}`
Output:
```2
```

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up