Leetcode 718. Maximum Length of Repeated Subarray
You are given two integer arrays nums1 and nums2. Find the length of the maximum length subarray that appears in both arrays.
nums1 and nums2?Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 100Answer: Return 0.
To solve the problem, we’ll use a dynamic programming (DP) approach. We can maintain a 2D DP array where dp[i][j] represents the length of the longest subarray ending at positions i in nums1 and j in nums2.
dp with dimensions (len1 + 1) x (len2 + 1) and initialize all elements to 0.nums1 (i from 1 to len1) and nums2 (j from 1 to len2).nums1[i-1] equals nums2[j-1], set dp[i][j] = dp[i-1][j-1] + 1.dp table, which will be the length of the longest common subarray.O(len1 * len2), where len1 and len2 are the lengths of nums1 and nums2, respectively. This is because we use nested loops to fill the DP table.O(len1 * len2) for storing the DP table.public class Solution {
public int findLength(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int[][] dp = new int[len1 + 1][len2 + 1]; // Create DP table
int maxLength = 0; // To keep track of the maximum length of the common subarray
// Fill the DP table
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1; // If elements match, increment length
maxLength = Math.max(maxLength, dp[i][j]); // Update maxLength
}
}
}
return maxLength; // Return the maximum length found
}
}
With this solution, you should be able to determine the length of the maximum length subarray that appears in both input 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?