Maximize Sum of Weights after Edge Removals - Problem

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:

  • Each node has an edge with at most k other nodes, where k is given.
  • The sum of the weights of the remaining edges is maximized.

Return the maximum possible sum of weights for the remaining edges after making the necessary removals.

Input & Output

Example 1 — Basic Tree with k=2
$ Input: edges = [[0,1,4],[1,2,2],[1,3,3]], k = 2
Output: 7
💡 Note: Node 1 has degree 3 but k=2, so we must remove at least 1 edge. To maximize weight, keep the two highest weight edges from node 1: [0,1,4] and [1,3,3] for total weight 4+3=7.
Example 2 — Degree Constraint Forces Removal
$ Input: edges = [[0,1,1],[1,2,2],[1,3,3],[1,4,4]], k = 2
Output: 7
💡 Note: Node 1 connects to 4 other nodes but can only keep 2 connections. To maximize weight, keep the two highest weight edges: [1,4,4] and [1,3,3] for total weight 4+3=7.
Example 3 — Single Edge
$ Input: edges = [[0,1,10]], k = 1
Output: 10
💡 Note: Only one edge exists and both nodes have degree 1 ≤ k=1, so keep the edge with weight 10.

Constraints

  • 1 ≤ n ≤ 104
  • 0 ≤ edges.length ≤ min(n × (n - 1) / 2, 104)
  • edges[i].length == 3
  • 0 ≤ ui < vi < n
  • 1 ≤ wi ≤ 106
  • 1 ≤ k ≤ n - 1

Visualization

Tap to expand
Maximize Sum of Weights after Edge Removals INPUT 0 1 2 3 w=4 w=2 w=3 edges = [[0,1,4],[1,2,2],[1,3,3]] k = 2 Each node can have at most k=2 edges connected ALGORITHM STEPS 1 Build Tree Create adjacency list 2 DFS from Root Process each subtree 3 Greedy Selection Pick top k edges by weight 4 Calculate Sum Sum weights of kept edges Edge Evaluation at Node 1: Edge Weight Keep? 1--0 4 OK 1--3 3 OK 1--2 2 OK FINAL RESULT 0 1 2 3 +4 +2 +3 Maximum Sum: 9 4 + 3 + 2 = 9 All edges kept! Node 1 has 3 edges (k=2) Key Insight: Use DFS with greedy selection: at each node, compute the gain from keeping each adjacent edge. Sort edges by weight and keep the top k edges per node to maximize total weight sum. Track two states: node included as child edge vs not included, then combine optimally. TutorialsPoint - Maximize Sum of Weights after Edge Removals | Greedy Edge Selection
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
248 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen