Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let findLength = function (a, b) {
- if (a.length === 0 || b.length === 0) {
- return 0;
- }
- // create our dynamic programming grid, which will cache our subproblem answers
- let cache = [];
- for (let row = 0; row < a.length + 1; row++) { // +1's are for empty string. We need the empty string row/col as a base case
- cache.push(new Array(b.length + 1).fill(0));
- }
- let max = 0;
- for (let row = 0; row < a.length + 1; row++) {
- for (let col = 0; col < b.length + 1; col++) {
- // base case, empty sets being solved against each other.
- if (row === 0 || col === 0) {
- cache[row][col] = 0;
- } else if (b[row - 1] === a[col - 1]) { // Match! The two numbers are equal.
- // the answer for this subset will be 1 + the subproblem answer for this cell is one above, and to the left, of the current cell.
- cache[row][col] = 1 + cache[row - 1][col - 1];
- // we have a new answer, compare it against our current max
- max = Math.max(max, cache[row][col]);
- }
- }
- }
- return max;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement