Approach
Breadth-first search
For Maximize Sum of Weights after Edge Removals, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 50 lines of Java from the credited upstream file 3367.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long maximizeSumOfWeights(int[][] edges, int k) {3 final int n = edges.length + 1;4 List<Pair<Integer, Integer>>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] edge : edges) {8 final int u = edge[0];9 final int v = edge[1];10 final int w = edge[2];11 graph[u].add(new Pair<>(v, w));12 graph[v].add(new Pair<>(u, w));13 }14 15 return dfs(graph, 0, -1, k).getValue();16 }17 18 19 20 21 private Pair<Long, Long> dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int k) {22 long weightSum = 0;23 Queue<Long> diffs = new PriorityQueue<>(Collections.reverseOrder());24 25 for (Pair<Integer, Integer> pair : graph[u]) {26 final int v = pair.getKey();27 final int w = pair.getValue();28 if (v == prev)29 continue;30 Pair<Long, Long> subResult = dfs(graph, v, u, k);31 final long subK1 = subResult.getKey();32 final long subK = subResult.getValue();33 weightSum += subK;34 35 diffs.offer(Math.max(0L, subK1 - subK + w));36 }37 38 long topK1 = 0;39 long topK = 0;40 41 for (int i = 0; i < k && !diffs.isEmpty(); ++i) {42 if (i < k - 1)43 topK1 += diffs.peek();44 topK += diffs.poll();45 }46 47 return new Pair<>(weightSum + topK1, weightSum + topK);48 }49}50