# 1035. Uncrossed Lines

We write the integers of `A` and `B` (in the order they are given) on two separate horizontal lines.

Now, we may draw *connecting lines*: a straight line connecting two numbers `A[i]` and `B[j]` such that:

* `A[i] == B[j]`;
* The line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.

Return the maximum number of connecting lines we can draw in this way.

**Example 1:**![](https://assets.leetcode.com/uploads/2019/04/26/142.png)

```
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
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.
```

**Example 2:**

```
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
```

**Example 3:**

```
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
```

**Note:**

1. `1 <= A.length <= 500`
2. `1 <= B.length <= 500`
3. `1 <= A[i], B[i] <= 2000`

{% hint style="info" %}
把題目給的例子連起來觀察答案，發現最多的未相交連線數量等於Longest Common Subsequence。所以又可以用DP來進算LCS了。LCS\[i]\[j]代表A\[0...i - 1]和B\[0...j - 1]之間的最多連線數量。\
dp state transition:\
LCS\[i]\[j] = LCS\[i - 1]\[j - 1] if A\[i - 1] == B\[j - 1]\
LCS\[i]\[j] = max(LCS\[i - 1]\[j], LCS\[i]\[j - 1]) if A\[i - 1] != B\[j - 1]
{% endhint %}

```cpp
// Dynamic Programming
int maxUncrossedLines(vector<int>& A, vector<int>& B) { // time: O(m * n); space: O(m * n)
    int m = A.size(), n = B.size();
    vector<vector<int> > LCS(m + 1, vector<int> (n + 1, 0));
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (A[i - 1] == B[j - 1])
                LCS[i][j] = LCS[i - 1][j - 1] + 1;
            else
                LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
        }
    }
    return LCS.back().back();
}
```

{% hint style="info" %}
因為每一個DP grid只用到左邊、上方、左上三個grids來更新，所以可以用一個1-D DP array搭配兩個變數就可以完成計算，不需要用到2D DP table。
{% endhint %}

```cpp
// Space Optimized Dynamic Programming
int maxUncrossedLines(vector<int>& A, vector<int>& B) { // time: O(m * n); space: O(n)
    int m = A.size(), n = B.size();
    vector<int> LCS(n + 1, 0);
    for (int i = 1; i <= m; ++i) {
        int upper_left = LCS[0];
        for (int j = 1; j <= n; ++j) {
            int upper = LCS[j];
            if (A[i - 1] == B[j - 1])
                LCS[j] = upper_left + 1;
            else
                LCS[j] = max(upper, LCS[j - 1]);
            upper_left = upper;
        }
    }
    return LCS.back();
}
```
