Leetcode #2497: Maximum Star Sum of a Graph
In this guide, we solve Leetcode #2497 Maximum Star Sum of a Graph in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Graph, Array, Sorting, Heap (Priority Queue)
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2
Output: 16
Explanation: The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
Python Solution
class Solution:
def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:
g = defaultdict(list)
for a, b in edges:
if vals[b] > 0:
g[a].append(vals[b])
if vals[a] > 0:
g[b].append(vals[a])
for bs in g.values():
bs.sort(reverse=True)
return max(v + sum(g[i][:k]) for i, v in enumerate(vals))
Complexity
The time complexity is O(n log n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.