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. 1 <= len(A), len(B) <= 1000
  2. 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/

 

posted @ 2018-11-08 21:08  Veritas_des_Liberty  阅读(184)  评论(0编辑  收藏  举报