#2497
Maximum Star Sum of a Graph
MediumArrayGreedyGraph TheorySortingHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages a more efficient way to gather neighbors and calculate the star sum. By using a priority queue, we can quickly access the top k neighbors without needing to sort them completely.
⚙️
Algorithm
4 steps- 1Step 1: Build a graph representation using an adjacency list.
- 2Step 2: For each node, gather its neighbors and push their values into a max-heap.
- 3Step 3: Extract the top k values from the heap to calculate the star sum.
- 4Step 4: Update the maximum star sum encountered.
solution.py21 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def maxStarSum(vals, edges, k):
6 graph = defaultdict(list)
7 for a, b in edges:
8 graph[a].append(b)
9 graph[b].append(a)
10
11 max_sum = float('-inf')
12 for i in range(len(vals)):
13 star_sum = vals[i]
14 neighbors = [vals[neighbor] for neighbor in graph[i]]
15 if neighbors:
16 largest_neighbors = heapq.nlargest(k, neighbors)
17 star_sum += sum(largest_neighbors)
18 max_sum = max(max_sum, star_sum)
19
20 return max_sum
21ℹ
Complexity note: The complexity is O(n log n) due to the use of a priority queue for extracting the top k values, which is more efficient than sorting all neighbors.
- 1The star sum can be maximized by focusing on the highest valued neighbors.
- 2Using a priority queue allows us to efficiently retrieve the top k neighbor values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.