#2538

Difference Between Maximum and Minimum Price Sum

Hard
ArrayDynamic ProgrammingTreeDepth-First SearchDepth-First SearchTree Traversal
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)

We can use a single DFS traversal to calculate the maximum and minimum price sums for paths starting from each node. By leveraging the tree structure, we can efficiently compute the required values without needing to re-root the tree multiple times.

⚙️

Algorithm

4 steps
  1. 1Step 1: Construct the graph from the edges.
  2. 2Step 2: Use a DFS to calculate the maximum and minimum price sums for paths starting from an arbitrary root.
  3. 3Step 3: Store the results in a way that allows us to compute the maximum difference efficiently.
  4. 4Step 4: Return the maximum difference found.
solution.py21 lines
1# Full working Python code
2from collections import defaultdict
3
4def maxDifference(n, edges, price):
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        max_sum = price[node]
12        min_sum = price[node]
13        for neighbor in graph[node]:
14            if neighbor != parent:
15                child_max, child_min = dfs(neighbor, node)
16                max_sum = max(max_sum, child_max + price[node])
17                min_sum = min(min_sum, child_min + price[node])
18        return max_sum, min_sum
19
20    max_sum, min_sum = dfs(0, -1)
21    return max_sum - min_sum

Complexity note: This complexity is efficient because we only traverse each node once during the DFS, leading to linear time complexity.

  • 1The minimum price sum is always the price of the root node.
  • 2Using DFS allows us to efficiently calculate the maximum and minimum price sums in a single traversal.

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