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: 9
💡 Note: Node 1 can connect to at most 2 nodes. We keep edges [0,1,4] and [1,3,3] for maximum weight 4+3=7. But optimal solution keeps [1,2,2] and [1,3,3] for weight 2+3=5, plus we can also keep other edges. Actually, we can keep all edges since each node has degree ≤ 2, giving total weight 4+2+3=9.
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 Edge Weights with Degree ConstraintsInput Tree0123w=5w=3w=4k=2 (max degree)Optimal Solution0123w=5 ✓w=4 ✓w=3 ✗Max Weight: 5 + 4 = 9Constraint CheckNode 0: degree 1 ≤ 2 ✓Node 1: degree 1 ≤ 2 ✓Node 2: would be 2 ≤ 2Node 3: degree 1 ≤ 2 ✓Remove lowest weight edgeto satisfy constraint
Understanding the Visualization
1
Input Tree
Undirected tree with weighted edges and degree limit k
2
Apply Constraints
Each node can connect to at most k other nodes
3
Maximize Weight
Select subset of edges with maximum total weight
Key Takeaway
🎯 Key Insight: Use tree DP to optimally select the best k edges for each node while considering parent connections
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