题目
https://leetcode.com/problems/maximum-length-of-repeated-subarray/
题解
Dynamic Programming [Accepted]
参考:官方题解
Intuition and Algorithm
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:]
. Whenever A[i] == B[j]
, we know dp[i][j] = dp[i+1][j+1] + 1
. Also, the answer is max(dp[i][j])
over all i, j
.
We can perform bottom-up dynamic programming to find the answer based on this recurrence. Our loop invariant is that the answer is already calculated correctly and stored in dp
for any larger i, j
.
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int[][] same = new int[nums1.length][nums2.length];
int max = 0;
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] == nums2[j]) {
same[i][j] = 1;
if (i > 0 && j > 0) same[i][j] += same[i - 1][j - 1];
max = Math.max(max, same[i][j]);
}
}
}
return max;
}
}