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
1/**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))910 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 }1617 let res = 01819 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 }2425 return res26}
Comments
Loading comments...
Tags
leetcode
recursion
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Longest Increasing Subsequence
Dynamic programming, top-down approach
Previous Post
LeetCode: Reduce Array Size to The Half
Hash table, sort by occurences then greedily remove