#2973

Find Number of Coins to Place in Tree Nodes

Hard
Dynamic ProgrammingTreeDepth-First SearchSortingHeap (Priority Queue)Depth-First SearchHeapsDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we will use Depth-First Search (DFS) while maintaining two heaps to efficiently track the top three positive costs and the bottom three non-positive costs in each subtree. This allows us to compute the maximum product in linear time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph representation of the tree using adjacency lists.
  2. 2Step 2: Perform a DFS traversal starting from the root node, maintaining two heaps for costs.
  3. 3Step 3: For each node, if its subtree size is less than 3, place 1 coin. Otherwise, calculate the maximum product using the top three positive costs from the heaps.
solution.py38 lines
1import heapq
2from collections import defaultdict
3
4def findCoins(edges, cost):
5    graph = defaultdict(list)
6    for a, b in edges:
7        graph[a].append(b)
8        graph[b].append(a)
9
10    def dfs(node, parent):
11        pos_heap = []
12        neg_heap = []
13        for neighbor in graph[node]:
14            if neighbor != parent:
15                p, n = dfs(neighbor, node)
16                pos_heap += p
17                neg_heap += n
18        pos_heap.append(cost[node])
19        pos_heap.sort(reverse=True)
20        neg_heap.sort()
21
22        if len(pos_heap) > 3:
23            pos_heap = pos_heap[:3]
24        if len(neg_heap) > 3:
25            neg_heap = neg_heap[:3]
26
27        max_product = 0
28        if len(pos_heap) == 3:
29            max_product = pos_heap[0] * pos_heap[1] * pos_heap[2]
30        result[node] = max(max_product, 0)
31        return pos_heap, neg_heap
32
33    result = [0] * len(cost)
34    dfs(0, -1)
35    for i in range(len(result)):
36        if result[i] == 0:
37            result[i] = 1
38    return result

Complexity note: This complexity is linear because we traverse each node once and maintain a limited number of costs in heaps, leading to efficient calculations.

  • 1Using heaps allows efficient tracking of top costs.
  • 2DFS is a natural fit for tree traversal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.