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
Minimum Increments to Equalize Leaf Paths INPUT Tree Structure (rooted at 0) 0 c=1 1 c=2 4 c=5 LEAF 2 c=3 LEAF 3 c=4 LEAF n = 5 edges = [[0,1],[1,2], [1,3],[0,4]] cost = [1,2,3,4,5] Green = Leaf nodes ALGORITHM STEPS 1 Compute Path Scores DFS to find all root-to-leaf path sums 2 Find Maximum Score Target = max path score All paths must equal this 3 Track Needed Increments For each path, find deficit to reach target score 4 Count Min Nodes Optimize by increasing nodes shared by multiple paths Path Score Analysis Path 0-->1-->2: 1+2+3 = 6 Path 0-->1-->3: 1+2+4 = 7 Path 0-->4: 1+5 = 6 Max Score (Target) = 7 Need to increase paths with 6 FINAL RESULT Optimal Node Increases 0 1 4 +1 2 +1 3 OK OUTPUT 2 2 nodes need cost increase: Node 2: 3 --> 4 (+1) Node 4: 5 --> 6 (+1) All paths now sum to 7 Key Insight: The target score must be the maximum existing path score (can only increase costs, not decrease). For minimum node changes, prioritize increasing nodes that appear in multiple deficient paths. DFS tracks cumulative path costs and identifies which leaf paths need balancing to reach the target. TutorialsPoint - Minimum Increments to Equalize Leaf Paths | Optimized DFS with Path Tracking
Asked in
Google 25 Amazon 18 Microsoft 15
58.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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