#2467
Most Profitable Path in a Tree
MediumArrayTreeDepth-First SearchBreadth-First SearchGraph TheoryDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we use a single DFS traversal to calculate the maximum net income for Alice while considering Bob's path. This allows us to efficiently compute the result in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Build the tree structure from the edges.
- 2Step 2: Use DFS to calculate the maximum income for Alice while keeping track of Bob's position.
- 3Step 3: Adjust the income based on whether Alice and Bob reach the same node.
solution.py20 lines
1def maxProfit(edges, amount, bob):
2 from collections import defaultdict
3 tree = defaultdict(list)
4 for a, b in edges:
5 tree[a].append(b)
6 tree[b].append(a)
7
8 def dfs(node, parent, bob_pos):
9 if node == bob_pos:
10 return amount[node] // 2
11 if len(tree[node]) == 1 and node != 0:
12 return amount[node]
13 max_income = float('-inf')
14 for neighbor in tree[node]:
15 if neighbor != parent:
16 income = dfs(neighbor, node, bob_pos)
17 max_income = max(max_income, income)
18 return max_income + (amount[node] // 2)
19
20 return dfs(0, -1, bob)ℹ
Complexity note: The time complexity is O(n) because we perform a single DFS traversal of the tree, visiting each node once. The space complexity is O(n) due to the recursion stack and the tree structure.
- 1Alice's path is flexible, while Bob's path is fixed.
- 2Simultaneous arrival at nodes affects income calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.