https://leetcode.com/problems/maximum-length-of-repeated-subarray/
(the link above is the problem)
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
nums1_str = ''.join([chr(x) for x in nums1])
max_str = ''
res = 0
for num in nums2:
max_str += chr(num)
if max_str in nums1_str:
res = max(res, len(max_str))
else:
max_str = max_str[1:]
return res
When I solved this problem with dp method, the speed is quite slow. Then I fould this solution, which is quite fast. I am curious that both method should be O(mn) in time, yet why the first one is much faster than the dp one, 267 ms vs 6417 ms. dp solution below
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
dp = [[0 for _ in range(1+n)] for _ in range(1+m)]
for i in range(1,m+1):
for j in range(1,n+1):
if nums1[i-1] == nums2[j-1]:
dp[i][j] = dp[i - 1][j - 1] + 1
return max(max(_) for _ in dp)