LeetCode Solutions

1035. Uncrossed Lines

Time:

Space:

			

class Solution {
 public:
  int maxUncrossedLines(vector<int>& A, vector<int>& B) {
    const int m = A.size();
    const int n = B.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j)
        dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1
                                        : max(dp[i - 1][j], dp[i][j - 1]);

    return dp[m][n];
  }
};
			

class Solution {
  public int maxUncrossedLines(int[] A, int[] B) {
    final int m = A.length;
    final int n = B.length;
    int[][] dp = new int[m + 1][n + 1];

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j)
        dp[i][j] =
            A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);

    return dp[m][n];
  }
}
			

class Solution:
  def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
    m = len(A)
    n = len(B)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
      for j in range(1, n + 1):
        dp[i][j] = dp[i - 1][j - 1] + 1 if A[i - 1] == B[j - 1] \
            else max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]