Maximum Length of Repeated Subarray
Leetcode algorithms problem 718:Maximum Length of Repeated Subarray
問題描述
Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
例子
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].思路
dp[i][j] = a[i] == b[j] ? dp[i + 1][j + 1] : 0;
dp[i][j] : max lenth of common subarray start at a[i] & b[j];
代碼
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<int> dp(B.size()+1);
int res = 0;
for (int i = A.size() - 1; i >= 0; i--) {
for (int j = 0; j < B.size(); j++) {
res = max(res, dp[j] = A[i] == B[j] ? 1 + dp[j + 1] : 0);
}
}
return res;
}
};
時間複雜度: O(mn)
空間複雜度: O(n)