Dsa
Trees
Medium
The Balanced Timber Cut
You are managing a logging operation. A tree is represented by N nodes, where each node has a weight (the amount of timber). You must cut exactly one edge to split the tree into two separate components. Your goal is to find the edge that, when removed, results in the minimum absolute difference between the total timber weights of the two components.
Input Format:
- Line 1: An integer N, the number of nodes.
- Line 2: N space-separated integers, where the i-th integer is the weight of node i+1.
- Next N-1 lines: Two integers u and v, representing an edge between node u and node v.
Output Format:
- A single integer: the minimum possible absolute difference.
Example:
Input:
3
10 20 15
1 2
2 3
Output:
5
(Removing 2-3 gives {10,20} and {15}, diff 15. Removing 1-2 gives {10} and {20,15}, diff 25. Min is 15? Wait, sum(1,2)=30, sum(3)=15, diff=15. Sum(1)=10, sum(2,3)=35, diff=25. Answer is 15.)
Key concepts
tree traversalsubtree sum
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now