# LeetCode: Maximum Length of Repeated Subarray Solution

Memoized recursion, somewhat similar to "Longest common subsequence"

## Approach

recursion(i, j)
returns longest common post-fix of
nums1.slice(0, i)
and
nums2.slice(0, j)

Result will be

max(recursion(i, j))
all over
i, j
pairs

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums13 * @param {number[]} nums24 * @return {number}5 */6var findLength = function (nums1, nums2) {7  const [m, n] = [nums1.length, nums2.length]8  const memo = Array.from({ length: m }, _ => Array(n).fill(null))9
10  const recursion = (i, j) => {11    if (i < 0 || j < 0) return 012    if (memo[i][j] !== null) return memo[i][j]13    const res = nums1[i] === nums2[j] ? 1 + recursion(i - 1, j - 1) : 014    return (memo[i][j] = res)15  }16
17  let res = 018
19  for (let i = 0; i < m; i++) {20    for (let j = 0; j < n; j++) {21      res = Math.max(res, recursion(i, j))22    }23  }24
25  return res26}```

## Tags

leetcode

recursion

dynamic programming

## Next Post

LeetCode: Longest Increasing Subsequence

Jul 9, 2021

Dynamic programming, top-down approach

## Previous Post

LeetCode: Reduce Array Size to The Half

Jul 7, 2021

Hash table, sort by occurences then greedily remove

Search Posts