Problem Description
Given an undirected graph consisting of n
nodes and a 0-indexed integer array vals
where vals[i]
denotes the value of the i-th
node, along with a 2D integer array edges
representing the connections between nodes, determine the maximum star sum of a star graph containing at most k
edges. A star graph is defined as a subgraph where there is a central node connected to a subset of its neighbors.
Key Insights
- A star graph is centered around one node and includes its neighbors.
- The star sum is calculated by adding the values of the central node and its neighbors.
- The challenge is to maximize the star sum while adhering to the limit of
k
edges. - It is important to consider only neighbors with positive values since including negative values would decrease the star sum.
Space and Time Complexity
Time Complexity: O(n + m log m), where n is the number of nodes and m is the number of edges (for sorting).
Space Complexity: O(n + m), for storing the adjacency list and neighbor values.
Solution
To solve the problem, we follow these steps:
- Create an adjacency list to represent the graph using the given edges.
- For each node, collect the values of its neighbors.
- Sort the neighbor values in descending order to prioritize the highest values.
- Calculate the star sum for each node by adding its value to the values of its top
k
neighbors (considering only positive values). - Return the maximum star sum found across all nodes.