Difference Between Maximum and Minimum Price Sum - Problem

There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.

The price sum of a given path is the sum of the prices of all nodes lying on that path.

The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.

Return the maximum possible cost amongst all possible root choices.

Input & Output

Example 1 — Linear Tree
$ Input: n = 3, edges = [[0,1],[1,2]], price = [2,3,1]
Output: 2
💡 Note: When root=0: paths [2+3=5, 2+3+1=6], cost=6-5=1. When root=1: paths [3+2=5, 3+1=4], cost=5-4=1. When root=2: path [1+3+2=6], cost=0. Maximum cost is 2 when we choose an optimal root.
Example 2 — Single Node
$ Input: n = 1, edges = [], price = [5]
Output: 0
💡 Note: Only one node, so there's only one path (the node itself) with sum 5. Max - min = 5 - 5 = 0.
Example 3 — Star Tree
$ Input: n = 4, edges = [[0,1],[0,2],[0,3]], price = [1,2,3,4]
Output: 3
💡 Note: When root=0: paths [1+2=3, 1+3=4, 1+4=5], cost=5-3=2. When root=1: paths [2+1=3, 2+1+3=6, 2+1+4=7], cost=7-3=4. Maximum cost across all roots is 4.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • edges.length = n - 1
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi
  • edges represents a valid tree
  • 1 ≤ price[i] ≤ 105

Visualization

Tap to expand
Tree Root Selection for Maximum CostOriginal Tree012price=2price=3price=1Root = 0012Paths: [2+3=5, 2+3+1=6]Cost: 6-5 = 1Root = 2210Path: [1+3+2=6]Cost: 6-6 = 0Maximum Cost = 2 (choosing optimal root)
Understanding the Visualization
1
Input Tree
Tree with nodes having associated prices
2
Choose Root
Try each node as root and calculate paths
3
Max Difference
Find maximum cost (max_path - min_path) across all roots
Key Takeaway
🎯 Key Insight: Different root choices create different path structures, affecting the cost calculation
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
8.5K Views
Medium Frequency
~35 min Avg. Time
189 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen