#2920
Maximum Points After Collecting Coins From All Nodes
HardArrayDynamic ProgrammingBit ManipulationTreeDepth-First SearchMemoizationDynamic ProgrammingDepth-First SearchMemoization
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)
The optimal approach uses dynamic programming with memoization to efficiently calculate the maximum points from each node while avoiding redundant calculations. We keep track of how many times we've used the halving operation to ensure we maximize our points.
⚙️
Algorithm
3 steps- 1Step 1: Build the tree using adjacency lists from the edges.
- 2Step 2: Use a depth-first search (DFS) to traverse the tree and calculate points for each node.
- 3Step 3: Maintain a memoization table to store results for each node and the number of times the halving operation has been used.
solution.py25 lines
1# Full working Python code
2class Solution:
3 def collectTheCoins(self, edges, coins, k):
4 from collections import defaultdict
5 tree = defaultdict(list)
6 for a, b in edges:
7 tree[a].append(b)
8 tree[b].append(a)
9
10 memo = {} # Memoization dictionary
11
12 def dfs(node, parent, t):
13 if (node, t) in memo:
14 return memo[(node, t)]
15 total_points = 0
16 for child in tree[node]:
17 if child != parent:
18 total_points += dfs(child, node, t)
19 collect_direct = coins[node] - k if coins[node] - k > 0 else -abs(coins[node] - k)
20 collect_half = coins[node] // 2
21 result = max(total_points + collect_direct, total_points + collect_half)
22 memo[(node, t)] = result
23 return result
24
25 return dfs(0, -1, 0)ℹ
Complexity note: The complexity is O(n) because we traverse each node once, and memoization allows us to avoid redundant calculations.
- 1Understanding the effects of each collection method is crucial for maximizing points.
- 2Using memoization can significantly reduce the time complexity by avoiding redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.