718. Maximum Length of Repeated Subarray
DP: Since a common subarray of A and B must start at some A[i] and B[j], let dp[i][j] be the longest common prefix of A[i:] and B[j:].
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int findLength = 0;
int[][] longest = new int[nums1.length + 1][nums2.length + 1];
longest[0][0] = 0;
for (int i = 1; i <= nums1.length; i++) {
longest[i][0] = 0;
}
for (int j = 1; j <= nums2.length; j++) {
longest[0][j] = 0;
}
for (int i = 1; i <= nums1.length; i++) {
for (int j = 1; j <= nums2.length; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
longest[i][j] = longest[i - 1][j - 1] + 1;
} else {
longest[i][j] = 0;
}
findLength = Math.max(findLength, longest[i][j]);
}
}
return findLength;
}
}