FastPrepMinimum Tree Value After Leaf Relocations
Problem · Tree

Minimum Tree Value After Leaf Relocations

Learn this problem
HardGoogle logoGoogleINTERNOA
See Google hiring insights

Problem statement

You are given an undirected tree with n nodes, rooted at node 1. Node i has the positive value values[i - 1].

You may perform at most k operations. In one operation:

  • Choose a non-root leaf in the current rooted tree.
  • Disconnect it from its parent and reconnect it as a child of any remaining node, including its former parent.

A node that becomes a leaf after earlier operations may be chosen in a later operation. The root itself is never moved.

After all operations, define the value of every node to be the sum of the original assigned values of all nodes in its final rooted subtree, including itself. Return the minimum possible sum of these final node values.

The answer can exceed the range of a 32-bit integer.

Function

minimumTreeValue(n: int, k: int, values: int[], edges: int[][]) → long

Examples

Example 1

n = 4k = 1values = [5,1,4,2]edges = [[1,2],[2,3],[2,4]]return = 21

Before any move, the total is 25. Move leaf 3 directly under the root. Its depth decreases from 2 to 1, reducing the total by 4. The resulting minimum is 21.

Example 2

n = 5k = 3values = [1,10,1,10,10]edges = [[1,2],[2,3],[2,4],[4,5]]return = 63

Move node 5, then the newly created leaf 4, and also move leaf 3, attaching each one to the root. The total decreases from 94 to 63.

Example 3

n = 1k = 0values = [7]edges = []return = 7

The tree contains only the root, so no operation is possible and its final subtree sum is 7.

Constraints

  • 1 <= n <= 1000
  • 0 <= k <= n - 1
  • values.length == n
  • 1 <= values[i] <= 10^9
  • edges.length == n - 1
  • Every edge is a pair [u, v] with 1 <= u, v <= n.
  • edges forms a valid undirected tree.

More Google problems

drafts saved locally
public long minimumTreeValue(int n, int k, int[] values, int[][] edges) {
  // write your code here
}
n4
k1
values[5,1,4,2]
edges[[1,2],[2,3],[2,4]]
expected21
checking account