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.
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
Approach #1: Dynamic programming
class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int ans = 0; int lenA = A.size(); int lenB = B.size(); vector<vector<int>> memo(lenA+1, vector<int>(lenB+1, 0)); for (int i = lenA-1; i >= 0; --i) { for (int j = lenB-1; j >= 0; --j) { if (A[i] == B[j]) { memo[i][j] = memo[i+1][j+1] + 1; ans = max(ans, memo[i][j]); } } } return ans; } };
Runtime: 92 ms, faster than 65.15% of C++ online submissions for Maximum Length of Repeated Subarray.
Analysis:
maybe using dynamic programming from back to front is the key to solve these similar questions.
there are some other ways to solve this problem.
https://leetcode.com/problems/maximum-length-of-repeated-subarray/
永远渴望,大智若愚(stay hungry, stay foolish)