MediumNo. 2497

Maximum Star Sum of a Graph — LeetCode 2497 Python Solution

Topics
Greedy, Graph, Array, Sorting, Heap (Priority Queue)
Reading time
2 min

The problem

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.

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.

Python solution

PythonSolution
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

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2497. Maximum Star Sum of a Graph is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2497. Maximum Star Sum of a Graph?

LeetCode 2497. Maximum Star Sum of a Graph is rated Medium on LeetCode.

What topics does LeetCode 2497. Maximum Star Sum of a Graph cover?

LeetCode 2497. Maximum Star Sum of a Graph is tagged Greedy, Graph, Array, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.