Given a rooted tree with edge costs, increase edge costs so every root-to-leaf path has the same total cost using the minimum number of increments.
You are given a rooted tree with n nodes labeled from 0 to n - 1. The root is node 0. Each non-root node has exactly one parent, and the edge from a node to its parent has a positive integer cost.
You may increase the cost of any edge by any non-negative integer amount. Your goal is to make all root-to-leaf path sums equal, while minimizing the total amount of increase applied across all edges.
Return the minimum total increment needed.
A root-to-leaf path sum is the sum of edge costs along the path from the root to a leaf node.
The tree can be processed bottom-up: each subtree can report the maximum path sum needed beneath it, and smaller child paths can be raised to match that maximum.
n, the number of nodes.n - 1 parent-cost relations for nodes 1..n-1, where each relation gives the parent of the node and the edge cost to that node.You may assume the input describes a valid rooted tree with root 0.
1 <= nExample 1
Input
n = 5 parents = [0, 0, 1, 1] costs = [3, 1, 2, 4]
Output
2
Explanation
The tree has edges 0->1 (3), 0->2 (1), 1->3 (2), and 1->4 (4).
Root-to-leaf sums are:
Raise the edge 0->2 by 6? That would be too much if done alone. Instead, equalize bottom-up:
Total increase is 2 + 8 = 10.
This illustrative example shows the bottom-up equalization idea.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.