You are given n nodes numbered 0 to n - 1, where node i has the value node_values[i]. The nodes form a complete graph: every pair of distinct nodes is joined by one undirected edge, and the edge between nodes i and j has weight node_values[i] * node_values[j].
You want to remove edges, and removing an edge costs its weight. You are also given an integer budget. A set of removed edges is valid when the graph that remains is still connected and the total weight of the removed edges is at most budget.
Among all valid sets, take one that removes the largest possible number of edges. If several valid sets remove that many edges, take the one with the smallest total weight. Return that total weight. If no edge can be removed, return 0.
Function Signature
def min_removal_cost(node_values: list[int], budget: int) -> int:
Rules
-
The graph has
n * (n - 1) / 2
edges, one per pair of distinct nodes. Node values may repeat.
-
The graph stays connected when every node can still reach every other node through the edges that were not removed.
-
Only the returned weight matters. When two valid sets have the same size and the same weight, either one gives the same answer.
Constraints
-
2 <= n <= 1000
-
1 <= node_values[i] <= 100
-
0 <= budget <= 10^9
Examples
Input: node_values = [1, 2, 3], budget = 10
Output: 2
The edges are (0, 1) with weight 2, (0, 2) with weight 3 and (1, 2) with weight 6. Removing two edges would cut a node off, so at most one edge can go. Any single edge can be removed from the triangle, and the cheapest one weighs 2.
Input: node_values = [3, 5, 7, 2], budget = 20
Output: 16
The edge weights are (0, 1) = 15, (0, 2) = 21, (0, 3) = 6, (1, 2) = 35, (1, 3) = 10 and (2, 3) = 14, for a total of 101. Removing three edges leaves a spanning tree, and the heaviest spanning tree uses 35, 21 and 14 for 70, so removing three edges costs at least 31, which is over the budget. Two edges fit: removing (0, 3) and (1, 3) costs 6 + 10 = 16, and node 3 stays connected through (2, 3).
Input: node_values = [4, 4, 4, 4], budget = 10
Output: 0
Every edge weighs 16, which is more than the budget, so no edge can be removed.