Sponsored
Sponsored
This approach uses a dynamic programming (DP) solution where we maintain a 2D array called dp
. The element dp[i][j]
represents the maximum number of lines that can be drawn without crossing up to the i-th element of nums1 and the j-th element of nums2.
The DP formulation is based on: if nums1[i] == nums2[j]
, then dp[i][j] = dp[i-1][j-1] + 1
. Otherwise, dp[i][j] = max(dp[i-1][j], dp[i][j-1])
.
The final answer is found in dp[m][n]
, where m and n are the lengths of nums1
and nums2
respectively. This approach runs in O(m * n) time complexity and uses O(m * n) space.
Time Complexity: O(m * n), where m and n are the lengths of nums1 and nums2.
Space Complexity: O(m * n), for the dp array.
1function maxUncrossedLines(A, B) {
2 const m = A.length, n = B.length;
3 const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
4
5 for (let i = 1; i <= m; i++) {
6 for (let j = 1; j <= n; j++) {
7 if (A[i - 1] === B[j - 1])
8 dp[i][j] = dp[i - 1][j - 1] + 1;
9 else
10 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
11 }
12 }
13 return dp[m][n];
14}
15
16const nums1 = [1, 4, 2];
17const nums2 = [1, 2, 4];
18console.log("Output:", maxUncrossedLines(nums1, nums2));
This JavaScript implementation uses arrays to form a dynamic programming 2D grid to map possible sequences of lines. The strategy involves iterating over each possible pair of indices between the two arrays, accumulating a higher score when equal elements are found, thus ensuring that the maximum number of uncrossed lines is calculated.
This approach is an optimization of the basic dynamic programming solution by reducing space complexity. Instead of utilizing a 2D array, we can use a single-dimensional array to store only the current and previous row information, thus reducing the space usage. This takes advantage of the fact that the current DP state depends only on the previous state, not all preceding states.
We maintain two 1D arrays, and they get updated in each iteration over the second array, resulting in reduced space complexity to O(min(m, n)).
Time Complexity: O(m * n), where m and n are the lengths of nums1 and nums2.
Space Complexity: O(min(m, n)), for the dp array.
public class Solution {
public int MaxUncrossedLines(int[] A, int[] B) {
if (A.Length < B.Length) return MaxUncrossedLines(B, A);
int m = A.Length, n = B.Length;
int[] dp = new int[n + 1];
for (int i = 1; i <= m; i++) {
int prev = 0;
for (int j = 1; j <= n; j++) {
int temp = dp[j];
if (A[i - 1] == B[j - 1])
dp[j] = prev + 1;
else
dp[j] = Math.Max(dp[j], dp[j - 1]);
prev = temp;
}
}
return dp[n];
}
public static void Main() {
Solution solution = new Solution();
int[] nums1 = {1, 4, 2};
int[] nums2 = {1, 2, 4};
Console.WriteLine("Output: " + solution.MaxUncrossedLines(nums1, nums2));
}
}
This C# version scales space use through a minimized rolling array dp
. The match-rematch mechanics propagate through pre-engagement checks, delivering calculated paths through single-dimensional traversal.