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.
1def maxUncrossedLines(A, B):
2 m, n = len(A), len(B)
3 dp = [[0] * (n + 1) for _ in range(m + 1)]
4 for i in range(1, m + 1):
5 for j in range(1, n + 1):
6 if A[i - 1] == B[j - 1]:
7 dp[i][j] = dp[i - 1][j - 1] + 1
8 else:
9 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
10 return dp[m][n]
11
12nums1 = [1, 4, 2]
13nums2 = [1, 2, 4]
14print("Output:", maxUncrossedLines(nums1, nums2))
The Python solution establishes a 2D list dp
to track the best solution so far for subarrays of nums1
and nums2
. The list is filled through nested loops by either incrementing the value when encountering matching elements from the two lists or propagating the maximum seen value otherwise.
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.
#include <iostream>
#include <algorithm>
using namespace std;
int maxUncrossedLines(vector<int>& A, vector<int>& B) {
if (A.size() < B.size()) return maxUncrossedLines(B, A);
vector<int> dp(B.size() + 1, 0);
for (int i = 1; i <= A.size(); ++i) {
int prev = 0;
for (int j = 1; j <= B.size(); ++j) {
int temp = dp[j];
if (A[i - 1] == B[j - 1])
dp[j] = prev + 1;
else
dp[j] = max(dp[j], dp[j - 1]);
prev = temp;
}
}
return dp[B.size()];
}
int main() {
vector<int> nums1 = {1, 4, 2};
vector<int> nums2 = {1, 2, 4};
cout << "Output: " << maxUncrossedLines(nums1, nums2) << endl;
return 0;
}
The C++ implementation follows the same logic of reducing space by using a 1D dp
array. Instead of a 2D board, a rolling solution tracks the current and previous states, benefiting from reduced memory overhead.