Minimum Increments to Equalize Leaf Paths - Problem
You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi] indicates an edge from node ui to vi.
Each node i has an associated cost given by cost[i], representing the cost to traverse that node. The score of a path is defined as the sum of the costs of all nodes along the path.
Your goal is to make the scores of all root-to-leaf paths equal by increasing the cost of any number of nodes by any non-negative amount. Return the minimum number of nodes whose cost must be increased to make all root-to-leaf path scores equal.
Input & Output
Example 1 — Basic Tree
$
Input:
n = 5, edges = [[0,1],[1,2],[1,3],[0,4]], cost = [1,2,3,4,5]
›
Output:
2
💡 Note:
Tree has paths: 0→1→2 (sum=6), 0→1→3 (sum=7), 0→4 (sum=6). Maximum sum is 7, so paths to nodes 2 and 4 need increments.
Example 2 — Balanced Tree
$
Input:
n = 3, edges = [[0,1],[0,2]], cost = [1,1,1]
›
Output:
0
💡 Note:
Both paths 0→1 and 0→2 have equal sums (2), so no increments needed.
Example 3 — Single Node
$
Input:
n = 1, edges = [], cost = [5]
›
Output:
0
💡 Note:
Only one node, no paths to equalize.
Constraints
- 1 ≤ n ≤ 105
- edges.length == n - 1
- 0 ≤ ui, vi ≤ n - 1
- 1 ≤ cost[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Tree with nodes having different costs
2
Calculate Path Sums
Find sums of all root-to-leaf paths
3
Identify Increments
Mark nodes on paths with less than maximum sum
Key Takeaway
🎯 Key Insight: Use DFS to find the maximum path sum, then count nodes on shorter paths that need increments
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code