718 Maximum Length of Repeated Subarray
Given two integer arrays
B, return the maximum length of an subarray that appears in both arrays.
The repeated subarray with maximum length is [3, 2, 1].
- 1.1 <= len(A), len(B) <= 1000
- 2.0 <= A[i], B[i] < 100
The Idea: First lets try to identify where the numbers within the array actually match. The first combination where they do match marks what may potentially begin as the longest maximum length of the two arrays. Once this is done, we need to identify the longest path. The way to do this can be done in two particular ways. Either we can count forwards
A(3,2,1) -> B(3,2,1)or we can count backwards
A(1,2,3) -> B(1,2,3). Because we will be iterating through the elements of arrays A and B, it is more natural to count forwards. Once we confirm a matching region in A that is also in B, how can be confirm that the previous position also matched? Well consider the example when we match (3,2) (elements 2 in indicies 3, and 2 in A and B respectfully). The elements that came before it are 2 and 1 (just -1 from there previous indices). So in the matrix, for we look at the upper left cell, we can identify whether the previous element matched. Eventually we can accumulate this among itself and basically maintain the total number of match elements so far. Then maximum element in the matrix will hence represent the length of the longest common subarray.
Complexity: O(n*m) time and space
import numpy as np
def findLength(self, A, B):
:type A: List[int]
:type B: List[int]
dp_m = np.zeros((len(A) + 1, len(B) + 1), dtype=np.int32)
for i in range(0, len(A)):
for j in range(0, len(B)):
if A[i] == B[j]:
dp_m[i+1][j+1] += dp_m[i][j] + 1