-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path2467-most-profitable-path-in-a-tree.js
108 lines (78 loc) · 2.33 KB
/
2467-most-profitable-path-in-a-tree.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* Time O(n) | Space O(n)
* Graph | DFS
* https://leetcode.com/problems/most-profitable-path-in-a-tree
* @param {number[][]} edges
* @param {number} bob
* @param {number[]} amount
* @return {number}
*/
var mostProfitablePath = function(edges, bob, amount) {
const tree = makeBiDirectionalTree(edges);
const reverseTree = makeParentLinks(tree);
const bobTime = {};
const bobDfs = (node, time) => {
bobTime[node] = time;
if (node === 0) return;
const parentNode = reverseTree[node];
bobDfs(parentNode, time+1);
}
bobDfs(bob, 0);
let max = -Infinity;
const visited = new Set();
const aliceDfs = (node, time, currScore) => {
if (visited.has(node)) return;
visited.add(node);
if (time < bobTime[node] || bobTime[node] === undefined) {
currScore = currScore + amount[node];
}
if (time === bobTime[node]) {
currScore = currScore + (amount[node]/2);
}
if (visited.has(tree[node][0]) && tree[node].length === 1) {
max = Math.max(currScore, max);
return;
}
const neighbors = tree[node];
for (let i = 0; i < neighbors.length; i++) {
const nextNode = neighbors[i];
aliceDfs(nextNode, time+1, currScore);
}
}
aliceDfs(0, 0, 0);
return max;
};
const makeBiDirectionalTree = (edges) => {
const tree = {};
for (let i = 0; i < edges.length; i++) {
const parent = edges[i][0];
const child = edges[i][1];
if (tree[parent]) {
tree[parent].push(child);
} else {
tree[parent] = [child]
}
if (tree[child]) {
tree[child].push(parent);
} else {
tree[child] = [parent];
}
}
return tree;
}
const makeParentLinks = (tree) => {
const reverseTree = {};
const visited = new Set();
const dfs = (parent, node) => {
if (visited.has(node)) return;
visited.add(node);
reverseTree[node] = parent;
const neighbors = tree[node] || [];
for (let i = 0; i < neighbors.length; i++) {
const nextNode = neighbors[i];
dfs(node, nextNode);
}
}
dfs(-1, 0);
return reverseTree;
}