Problem
Minimum Town Sum Difference
Learn this problemProblem statement
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.
Function
minTownsDiff(n: int, towns: int[], roads: int[][]) → intExamples
Example 1
n = 2towns = [10,20]roads = [[1,2]]return = 10Deleting the only edge creates components with sums 10 and 20, so the difference is 10.
Example 2
n = 5towns = [1,2,3,4,5]roads = [[1,2],[1,3],[3,4],[3,5]]return = 5Deleting 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
- Longest Subarray with Sum at Most KOA · Seen Jul 2026
- Count Prefix Matches in a Sorted ArrayONSITE INTERVIEW · Seen Jul 2026
- Decode StringONSITE INTERVIEW · Seen Jul 2026
- Phone Keypad Letter CombinationsONSITE INTERVIEW · Seen Jul 2026
- Split a Log Outside QuotesONSITE INTERVIEW · Seen Jul 2026
- Ad Score Scheduler With DelayONSITE INTERVIEW · Seen Jul 2026
- Alternating-Color Binary Tree RootsONSITE INTERVIEW · Seen Jul 2026
- Route Pattern MatcherONSITE INTERVIEW · Seen Jul 2026