There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 2D integer array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi in the tree.
Your task is to remove zero or more edges such that:
k other nodes, where k is given.Return the maximum possible sum of weights for the remaining edges after making the necessary removals.
Example 1:
Input: edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2
Output: 22
Explanation:

[0, 2, 2], ensuring that no node has edges with more than k = 2 nodes.Example 2:
Input: edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3
Output: 65
Explanation:
k = 3 nodes, we don't remove any edges.Constraints:
2 <= n <= 1051 <= k <= n - 1edges.length == n - 1edges[i].length == 30 <= edges[i][0] <= n - 10 <= edges[i][1] <= n - 11 <= edges[i][2] <= 106edges form a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This problem asks for the maximum sum of tree edge weights such that every node has degree at most k. We can root the tree arbitrarily and compute the optimal values using tree dynamic programming. For each node, we determine the best total weight when retaining at most k incident child edges, as well as at most k - 1 child edges to leave room for the edge to its parent.
Here's how the algorithm would work step-by-step:
import sys
def maximize_sum_of_weights(edges, k):
sys.setrecursionlimit(200000)
node_count = len(edges) + 1
adjacency_list = [[] for _ in range(node_count)]
# Build the adjacency list for the tree.
for node_u, node_v, weight in edges:
adjacency_list[node_u].append((node_v, weight))
adjacency_list[node_v].append((node_u, weight))
# Define dynamic programming states for each node.
def depth_first_search(current_node, parent_node):
base_sum = 0
differences = []
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node == parent_node:
continue
child_without_parent_edge, child_with_parent_edge = depth_first_search(neighbor_node, current_node)
base_sum += child_without_parent_edge
gain = child_with_parent_edge + edge_weight - child_without_parent_edge
if gain > 0:
differences.append(gain)
# Sort gains in descending order to choose the best edges.
differences.sort(reverse=True)
sum_k = base_sum + sum(differences[:k])
sum_k_minus_one = base_sum + sum(differences[:k - 1])
return sum_k, sum_k_minus_one
best_total, _ = depth_first_search(0, -1)
return best_total
This problem asks for the maximum total weight of remaining edges in a tree such that every node has degree at most k. We can solve this with tree dynamic programming by determining for each node the maximum weight achievable in its subtree under two conditions: whether the edge to its parent is retained or removed. By computing the net gain of retaining an edge to each child, we greedily select the most profitable edges up to the capacity limit.
Here's how the algorithm would work step-by-step:
import sys
def maximize_sum_of_weights(edges, k):
sys.setrecursionlimit(200000)
node_count = len(edges) + 1
adjacency_list = [[] for _ in range(node_count)]
# Build the adjacency list for the undirected tree
for u_node, v_node, weight in edges:
adjacency_list[u_node].append((v_node, weight))
adjacency_list[v_node].append((u_node, weight))
# Recursively compute the best sums for keeping or removing the parent edge
def dfs(current_node, parent_node):
base_sum = 0
gains = []
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node == parent_node:
continue
child_keep, child_remove = dfs(neighbor_node, current_node)
base_sum += child_remove
gain = child_keep + edge_weight - child_remove
if gain > 0:
gains.append(gain)
# Sort the positive gains in descending order to greedily take the best
gains.sort(reverse=True)
# Best weight sum if at most k - 1 child edges are kept
with_parent = base_sum + sum(gains[:k - 1])
# Best weight sum if at most k child edges are kept
without_parent = base_sum + sum(gains[:k])
return with_parent, without_parent
_, total_max_weight = dfs(0, -1)
return total_max_weight
| Case | How to Handle |
|---|---|
| Tree consists of only a single node with no edges | Return zero since the sum of remaining edge weights is empty and no edges exist to remove |
| Degree limit is zero or less than the maximum possible degree in the tree | Greedily evaluate subtree optimal choices to ensure node degrees strictly respect the given upper bound |
| Degree limit is greater than or equal to the maximum degree of any node in the tree | Keep all original edges as no node exceeds the degree constraint naturally |
| Edge weights contain negative values | Only include an edge if its contribution combined with child subtrees yields a net positive weight increase |
| Extremely deep line graph tree causing potential recursion limit issues | Use iterative post-order traversal or increase the stack limit to prevent stack overflow errors |
| Star graph where a single central node is connected to a very large number of leaf nodes | Sort the child edge gains for the central node and greedily pick the top k edges up to the degree limit |
| Large tree scale reaching maximum constraints where edge weights sum up to large integers | Use 64-bit integers to prevent any potential arithmetic overflow during weight sum accumulation |
| Disconnected tree components or forest instead of a single tree | The problem statement specifies an undirected tree, but standard tree DFS handles any rooted acyclic component structure natively |