Problem Description
Given an undirected graph where each node has an associated value, the goal is to select a star graph (a central node with a subset of its neighbors) that maximizes the sum of node values. The star graph may include at most k edges. Essentially, for each potential center node, you may choose up to k of its neighbors (only if they add positive contribution) to maximize the total sum.
Key Insights
- Each star graph has a center node; start the sum with the center's value.
- The contribution of a neighbor is only beneficial if its value is positive.
- For each node, sort its neighbors by value in descending order to consider the highest contributions first.
- Because the graph is undirected, every edge allows both endpoints to potentially be the center of a star.
Space and Time Complexity
Time Complexity: O(n log n + m), where n is the number of nodes and m is the number of edges. The dominant cost comes from creating the adjacency list and sorting the neighbor lists for each node. Space Complexity: O(n + m) due to storing the graph in an adjacency list format.
Solution
The solution follows these steps:
- Build an adjacency list where each node points to a list of its neighbors' values.
- For each node (considered as the potential star center), sort its neighbor list in descending order.
- Start with the center node's value, and add up to k neighbor values if they are positive.
- Track the maximum result obtained over all centers. This greedy approach ensures that for every node, only the most beneficial edges (neighbors with positive values) are selected.