Problem · Tree
Divide Tree Nodes
Learn this problemProblem statement
You are given an undirected tree with n nodes. Node x has value A[x].
Partition the nodes into the minimum possible number of groups such that no two adjacent nodes belong to the same group.
For a pair of nodes (u, v) in one group, its value is |A[u] - A[v]|. The cost of a group is the maximum total pair value obtainable by pairing nodes in that group, where every node may be used in at most one pair and some nodes may remain unpaired.
Return the sum of the costs of all groups in the minimum-group partition.
Function
divideTreeNodes(n: int, A: int[], edges: int[][]) → longExamples
Example 1
n = 5A = [12, 17, 14, 13, 16]edges = [[1, 2], [1, 3], [1, 5], [2, 4]]return = 4One minimum-group partition is {1,4} and {2,3,5}. Their maximum pairing costs are |12-13| = 1 and |17-14| = 3, so the answer is 1 + 3 = 4.
Constraints
1 ≤ T ≤ 101 ≤ N ≤ 1051 ≤ A[i] ≤ 1091 ≤ U, V ≤ N
More Google problems
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026