Longest Path With Different Adjacent Characters
/**
* @param {number[]} parent
* @param {string} s
* @return {number}
*/
var longestPath = function(parent, s) {
let n = parent.length;
let ans = 1;
let distance = new Array(n).fill(0);
let adj = [];
for (let i = 0; i < n; i++) {
adj[i] = new Array();
}
for (let i = 1; i < n; i++) {
adj[parent[i]].push(i);
}
console.log(adj);
const getLongestPath = (source) => {
distance[source] = 1;
for (let node of adj[source].values()) {
getLongestPath(node);
if (s[source] !== s[node]) {
ans = Math.max(ans, distance[source] + distance[node]);
distance[source] = Math.max(
distance[source],
distance[node] + 1
);
}
}
};
getLongestPath(0);
return ans;
};
Top comments (0)