Approach
Breadth-first search
For Maximum Star Sum of a Graph, 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
- 31 lines of Java from the credited upstream file 2497.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
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 int maxStarSum(int[] vals, int[][] edges, int k) {3 final int n = vals.length;4 int ans = Integer.MIN_VALUE;5 List<Pair<Integer, Integer>>[] graph = new List[n];6 Arrays.setAll(graph, i -> new ArrayList<>());7 8 for (int[] edge : edges) {9 final int u = edge[0];10 final int v = edge[1];11 graph[u].add(new Pair<>(v, vals[v]));12 graph[v].add(new Pair<>(u, vals[u]));13 }14 15 for (int i = 0; i < n; ++i) {16 Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());17 for (Pair<Integer, Integer> pair : graph[i]) {18 final int val = pair.getValue();19 if (val > 0)20 maxHeap.offer(val);21 }22 int starSum = vals[i];23 for (int j = 0; j < k && !maxHeap.isEmpty(); ++j)24 starSum += maxHeap.poll();25 ans = Math.max(ans, starSum);26 }27 28 return ans;29 }30}31