Skip to content

Commit c18deae

Browse files
committed
https://leetcode.cn/problems/most-profitable-path-in-a-tree
1 parent 03f758e commit c18deae

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@ https://leetcode.cn/problems/design-movie-rental-system/
127127

128128
https://leetcode.cn/problems/XxZZjK/
129129

130+
https://leetcode.cn/problems/most-profitable-path-in-a-tree
131+
130132
https://leetcode.cn/problems/magical-string/
131133

132134
https://leetcode.cn/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
export default function mostProfitablePath(
2+
edges: number[][],
3+
bob: number,
4+
amount: number[],
5+
): number {
6+
const g: number[][] = amount.map(() => []);
7+
8+
for (const [x, y] of edges) {
9+
g[x].push(y);
10+
g[y].push(x);
11+
}
12+
const bobTime = amount.map(() => Infinity);
13+
function dfsBob(x: number, fa: number, t: number): boolean {
14+
if (x === 0) {
15+
bobTime[x] = t;
16+
return true;
17+
}
18+
let found0 = false;
19+
20+
for (const y of g[x]) {
21+
if (y != fa && dfsBob(y, x, t + 1)) {
22+
found0 = true;
23+
}
24+
}
25+
if (found0) {
26+
bobTime[x] = t; // 只有可以到达 0 才标记访问时间
27+
}
28+
return found0;
29+
}
30+
dfsBob(bob, -1, 0);
31+
g[0].push(-1);
32+
let ans = -Infinity;
33+
34+
function dfsAlice(x: number, fa: number, aliceTime: number, sum: number) {
35+
if (aliceTime < bobTime[x]) {
36+
sum += amount[x];
37+
} else if (aliceTime == bobTime[x]) {
38+
sum += amount[x] / 2;
39+
}
40+
if (g[x].length == 1) {
41+
// 叶子
42+
ans = Math.max(ans, sum); // 更新答案
43+
return;
44+
}
45+
for (const y of g[x]) {
46+
if (y != fa) {
47+
dfsAlice(y, x, aliceTime + 1, sum);
48+
}
49+
}
50+
}
51+
dfsAlice(0, -1, 0, 0);
52+
return ans;
53+
}

0 commit comments

Comments
 (0)