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.
1import java.util.*;
2
3public class Solution {
4 public int maxUncrossedLines(int[] A, int[] B) {
5 int m = A.length, n = B.length;
6 int[][] dp = new int[m + 1][n + 1];
7 for (int i = 1; i <= m; i++) {
8 for (int j = 1; j <= n; j++) {
9 if (A[i - 1] == B[j - 1])
10 dp[i][j] = dp[i - 1][j - 1] + 1;
11 else
12 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
13 }
14 }
15 return dp[m][n];
16 }
17
18 public static void main(String[] args) {
19 Solution solution = new Solution();
20 int[] nums1 = {1, 4, 2};
21 int[] nums2 = {1, 2, 4};
22 System.out.println("Output: " + solution.maxUncrossedLines(nums1, nums2));
23 }
24}
This Java solution also employs a 2D dp
array to store the maximum lines possible up to each index pair. The process builds on previous solutions by iterating through both arrays and updating the dp
array based on whether the current elements are equal. The final result is found in dp[m][n]
, which contains the maximum number of uncrossed lines.
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.
This Java implementation opts for space efficiency by adopting a single-dimension array technique. It checks element matches and, if found, leverages a rolling update to optimize the solution.
When the arrays are of unequal lengths, swapping ensures the smaller array size determines space usage.