-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path1035-uncrossed-lines.js
More file actions
34 lines (33 loc) · 878 Bytes
/
1035-uncrossed-lines.js
File metadata and controls
34 lines (33 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {number[]} A
* @param {number[]} B
* @return {number}
*/
var maxUncrossedLines = function(A, B) {
const aLen = A.length
const bLen = B.length
const row = Array(bLen).fill(undefined)
const matrix = Array(aLen).fill(undefined)
for(let i=0; i<aLen; i++) {
matrix[i] = Array.from(row)
}
const getMaxTopOrLeft = (i,j) => {
let top = (i-1<0) ? 0 : matrix[i-1][j]
let left = (j-1<0) ? 0 : matrix[i][j-1]
return Math.max(top, left)
}
const getDiag = (i,j) => {
return (i-1 >=0 && j-1 >= 0) ? matrix[i-1][j-1] : 0
}
const getSelf = (i,j) => {
return A[i] === B[j] ? 1 : 0
}
for(let i=0; i<aLen; i++) {
for(let j=0; j<bLen; j++) {
let option1 = getDiag(i,j) + getSelf(i,j)
let option2 = getMaxTopOrLeft(i,j)
matrix[i][j] = Math.max(option1, option2)
}
}
return matrix[aLen-1][bLen-1]
};