#2285
Maximum Total Importance of Roads
MediumGreedyGraph TheorySortingHeap (Priority Queue)Greedy AlgorithmsGraph TheorySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n + m log m) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n + m log m)Space O(n)
Instead of checking all permutations, we can focus on the degree of each city. Cities with more connections (higher degrees) should get higher values to maximize the importance of the roads they connect.
⚙️
Algorithm
4 steps- 1Step 1: Count the degree of each city based on the roads provided.
- 2Step 2: Sort the cities by their degree in descending order.
- 3Step 3: Assign values from n down to 1 based on the sorted order of cities.
- 4Step 4: Calculate the total importance using the assigned values.
solution.py10 lines
1def maxTotalImportance(n, roads):
2 degree = [0] * n
3 for a, b in roads:
4 degree[a] += 1
5 degree[b] += 1
6 sorted_cities = sorted(range(n), key=lambda x: degree[x], reverse=True)
7 total_importance = 0
8 for i, city in enumerate(sorted_cities):
9 total_importance += (i + 1) * degree[city]
10 return total_importanceℹ
Complexity note: The time complexity is O(n + m log m), where n is the number of cities and m is the number of roads. The sorting step dominates the complexity. The space complexity is O(n) for storing the degree of each city.
- 1Cities with higher degrees should receive higher values to maximize road importance.
- 2Sorting cities by their degree allows for optimal value assignment.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.