Description
Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].
Note:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
Solution
DP, time O(m * n), space O(m * n)
常规的DP题。
class Solution {
public int findLength(int[] A, int[] B) {
int m = A.length;
int n = B.length;
// dp[i + 1][j + 1] is the length of longest common subarray
// ending with nums[i] and nums[j]
int[][] dp = new int[m + 1][n + 1];
int maxLen = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (A[i] != B[j]) {
continue;
}
dp[i + 1][j + 1] = 1 + dp[i][j];
maxLen = Math.max(maxLen, dp[i + 1][j + 1]);
}
}
return maxLen;
}
}