Skip to content

Commit 5af0034

Browse files
authored
Create 2246-longest-path-with-different-adjacent-characters.js
1 parent 73847e3 commit 5af0034

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} parent
3+
* @param {string} s
4+
* @return {number}
5+
*/
6+
var longestPath = function(parent, s) {
7+
let n = s.length, res = 0;
8+
const {max} = Math
9+
let children = Array.from({ length: n}, () => Array());
10+
for (let i = 1; i < n; ++i) children[parent[i]].push(i);
11+
dfs(children, s, 0);
12+
return res;
13+
14+
function dfs(children, s, i) {
15+
let big1 = 0, big2 = 0;
16+
for (let j of (children[i] || [])) {
17+
let cur = dfs(children, s, j);
18+
if (s[i] == s[j]) continue;
19+
if (cur > big2) big2 = cur;
20+
if (big2 > big1) {
21+
let tmp = big1
22+
big1 = big2
23+
big2 = tmp
24+
};
25+
}
26+
res = max(res, big1 + big2 + 1);
27+
return big1 + 1;
28+
}
29+
};
30+
31+

0 commit comments

Comments
 (0)