Approach
Depth-first search
For Most Profitable Path in a Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 60 lines of Python from the credited upstream file 2467.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def mostProfitablePath(3 self,4 edges: list[list[int]],5 bob: int,6 amount: list[int],7 ) -> int:8 n = len(amount)9 tree = [[] for _ in range(n)]10 parent = [0] * n11 aliceDist = [-1] * n12 13 for u, v in edges:14 tree[u].append(v)15 tree[v].append(u)16 17 18 def dfs(u: int, prev: int, d: int) -> None:19 parent[u] = prev20 aliceDist[u] = d21 for v in tree[u]:22 if aliceDist[v] == -1:23 dfs(v, u, d + 1)24 25 dfs(0, -1, 0)26 27 28 29 30 31 u = bob32 bobDist = 033 while u != 0:34 if bobDist < aliceDist[u]:35 amount[u] = 036 elif bobDist == aliceDist[u]:37 amount[u] = 238 u = parent[u]39 bobDist += 140 41 return self._getMoney(tree, 0, -1, amount)42 43 def _getMoney(44 self,45 tree: list[list[int]],46 u: int,47 prev: int,48 amount: list[int],49 ) -> int:50 51 if len(tree[u]) == 1 and tree[u][0] == prev:52 return amount[u]53 54 maxPath = -math.inf55 for v in tree[u]:56 if v != prev:57 maxPath = max(maxPath, self._getMoney(tree, v, u, amount))58 59 return amount[u] + maxPath60