Skip to content

Commit c77f5be

Browse files
2467_Most_Profitable_Path_in_Tree.java
1 parent 52799a9 commit c77f5be

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Problem NUmber: 2467
2+
3+
// Most Profitable path in a Tree.
4+
5+
class Solution {
6+
public int mostProfitablePath(int[][] edges, int bob, int[] amount) {
7+
final int n = amount.length;
8+
List<Integer>[] tree = new List[n];
9+
int[] parent = new int[n];
10+
int[] aliceDist = new int[n];
11+
Arrays.fill(aliceDist, -1);
12+
13+
for (int i = 0; i < n; ++i)
14+
tree[i] = new ArrayList<>();
15+
16+
for (int[] edge : edges) {
17+
final int u = edge[0];
18+
final int v = edge[1];
19+
tree[u].add(v);
20+
tree[v].add(u);
21+
}
22+
23+
dfs(tree, 0, -1, 0, parent, aliceDist);
24+
25+
// Modify the amount along the path from node Bob to node 0.
26+
// For each node,
27+
// 1. If Bob reaches earlier than Alice does, change the amount to 0.
28+
// 2. If Bob and Alice reach simultaneously, devide the amount by 2.
29+
for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist)
30+
if (bobDist < aliceDist[u])
31+
amount[u] = 0;
32+
else if (bobDist == aliceDist[u])
33+
amount[u] /= 2;
34+
35+
return getMoney(tree, 0, -1, amount);
36+
}
37+
38+
// Fills `parent` and `dist`.
39+
private void dfs(List<Integer>[] tree, int u, int prev, int d, int[] parent, int[] dist) {
40+
parent[u] = prev;
41+
dist[u] = d;
42+
for (final int v : tree[u]) {
43+
if (dist[v] == -1)
44+
dfs(tree, v, u, d + 1, parent, dist);
45+
}
46+
}
47+
48+
private int getMoney(List<Integer>[] tree, int u, int prev, int[] amount) {
49+
// a leaf node
50+
if (tree[u].size() == 1 && tree[u].get(0) == prev)
51+
return amount[u];
52+
53+
int maxPath = Integer.MIN_VALUE;
54+
for (final int v : tree[u])
55+
if (v != prev)
56+
maxPath = Math.max(maxPath, getMoney(tree, v, u, amount));
57+
58+
return amount[u] + maxPath;
59+
}
60+
}

0 commit comments

Comments
 (0)