Skip to content

Commit 008496e

Browse files
authored
Create 2467-most-profitable-path-in-a-tree.js
1 parent ad1eed4 commit 008496e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {number[][]} edges
3+
* @param {number} bob
4+
* @param {number[]} amount
5+
* @return {number}
6+
*/
7+
const mostProfitablePath = function(edges, bob, amount) {
8+
const graph = [], depth = [], parent = []
9+
for(const [u, v] of edges) {
10+
if(graph[u] == null) graph[u] = []
11+
if(graph[v] == null) graph[v] = []
12+
graph[u].push(v)
13+
graph[v].push(u)
14+
}
15+
dfs(0)
16+
let cur = bob, bobh = 0
17+
while(cur) {
18+
if(depth[cur] > bobh) amount[cur] = 0
19+
else if(depth[cur] === bobh) amount[cur] /= 2
20+
21+
bobh++
22+
cur = parent[cur]
23+
}
24+
25+
// console.log(depth, parent, amount)
26+
27+
return dfs2(0)
28+
29+
function dfs(node, p = 0, d = 0) {
30+
parent[node] = p
31+
depth[node] = d
32+
for(const e of graph[node]) {
33+
if(e === p) continue
34+
dfs(e, node, d + 1)
35+
}
36+
}
37+
38+
function dfs2(node, p = 0) {
39+
let res = amount[node]
40+
let ma = -Infinity
41+
for(const e of graph[node]) {
42+
if(e === p) continue
43+
ma = Math.max(ma, dfs2(e, node))
44+
}
45+
if(ma === -Infinity) return res
46+
return res + ma
47+
}
48+
};

0 commit comments

Comments
 (0)