Maximum Star Sum of a Graph

Solution

Implementation

import math
from collections import defaultdict

class Solution:
    def maxStarSum(self, vals: list[int], edges: list[list[int]], k: int) -> int:
        # Step 1: Build the graph, tracking ONLY positive neighbor values
        graph = defaultdict(list)
        for u, v in edges:
            if vals[v] > 0:
                graph[u].append(vals[v])
            if vals[u] > 0:
                graph[v].append(vals[u])
        
        max_star_sum = -math.inf
        
        # Step 2 & 3: Check every node as a potential center
        for i, center_val in enumerate(vals):
            # Sort this center's positive neighbors from largest to smallest
            neighbors = sorted(graph[i], reverse=True)
            
            # Take at most k neighbors
            current_star_sum = center_val + sum(neighbors[:k])
            
            # Update the global maximum
            max_star_sum = max(max_star_sum, current_star_sum)
            
        return max_star_sum