Leetcode 718. Maximum Length of Repeated Subarray
Given two integer arrays nums1 and nums2, return the length of the longest common subarray that appears in both arrays.
nums1 and nums2?
nums1 and nums2 will be in the range [1, 1000].0.We will use dynamic programming to solve this problem efficiently.
dp[i][j] represent the length of the longest common subarray that ends at index i-1 in nums1 and index j-1 in nums2.dp of size (len(nums1)+1) x (len(nums2)+1) with all elements set to 0.nums1[i-1] == nums2[j-1], then dp[i][j] = dp[i-1][j-1] + 1.dp[i][j] remains 0.max_len to track the maximum value in the dp array during the traversal.max_len will be the length of the longest common subarray.#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size();
int n2 = nums2.size();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));
int max_len = 0;
for (int i = 1; i <= n1; ++i) {
for (int j = 1; j <= n2; ++j) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
max_len = max(max_len, dp[i][j]);
}
// No need to set dp[i][j] to 0 if elements don't match because
// it's already initialized to 0.
}
}
return max_len;
}
};
Time Complexity: O(n1 * n2) where n1 is the length of nums1 and n2 is the length of nums2. This is because we are using two nested loops to fill the dp array.
Space Complexity: O(n1 * n2) for storing the dp array of size (n1+1) x (n2+1).
With this solution, we effectively find the length of the longest common subarray between the two given arrays.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?