#2322
Minimum Score After Removals on a Tree
specialist · 915 · lc hard +31 · verified · 76.2% accepted · 814 likes · top 87%
Description
There is an undirected connected tree with n nodes labeled 0 to n - 1 and n - 1 edges.
You are given a 0-indexed integer array nums of length n (where nums[i] is the value at node i) and a 2D integer array edges where edges[i] = [ai, bi] is an edge in the tree.
Remove exactly two distinct edges to split the tree into three connected components. For each such split:
- Compute the XOR of node values within each component.
- The score is the difference between the maximum and minimum of the three XOR values.
Return the minimum score over all valid pairs of edge removals.
Example 1:
Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 9
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.
- The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1.
- The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5.
The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.
It can be shown that no other pair of removals will obtain a smaller score than 9.
Example 2:
Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]
Output: 0
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.
- The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.
- The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.
The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.
We cannot obtain a smaller score than 0.
Code
1
2
3