You are given a tree with n nodes numbered from 1 to n and n - 1 bidirectional edges. Node i + 1 has towns[i] towns.
Delete exactly one edge. This splits the tree into two connected components.
Return the minimum possible absolute difference between the total number of towns in the two resulting components.
Examples
01 · Example 1
n = 2 towns = [10,20] roads = [[1,2]] return = 10
Deleting the only edge creates components with sums 10 and 20, so the difference is 10.
02 · Example 2
n = 5 towns = [1,2,3,4,5] roads = [[1,2],[1,3],[3,4],[3,5]] return = 5
Deleting edge [1,3] gives component sums 12 and 3, difference 9. Deleting edge [3,5] gives sums 5 and 10, difference 5, which is minimum.
Constraints
1 <= n <= 10^5towns.length == n1 <= towns[i] <= 10^4roads.length == n - 1roadsforms a tree.
More Google problems
- Consolidate On-Call RotationsOA · Seen Jun 2026
- Detonate Bombs with Chain ReactionsONSITE INTERVIEW · Seen May 2026
- Evaluate a Nested Math ExpressionONSITE INTERVIEW · Seen May 2026
- Tic-Tac-Toe Game StatusPHONE SCREEN · Seen May 2026
- Longest Dictionary TokenizationPHONE SCREEN · Seen May 2026
- Minimum Cars for Rental RequestsONSITE INTERVIEW · Seen Apr 2026
- Shortest Path with Mandatory WaypointONSITE INTERVIEW · Seen Apr 2026
- Count Divisible Coin SelectionsOA · Seen Dec 2025
public int minTownsDiff(int n, int[] towns, int[][] roads) {
// write your code here
}n2
towns[10,20]
roads[[1,2]]
expected10
sign in to submit