Maximum Total Importance of Roads - Problem
Maximum Total Importance of Roads

Imagine you're a city planner tasked with optimizing the economic value of transportation infrastructure! You have n cities numbered from 0 to n-1, connected by bidirectional roads.

Your mission: assign each city a unique importance value from 1 to n. The importance of each road is calculated as the sum of the importance values of the two cities it connects.

Goal: Maximize the total importance of all roads by strategically assigning values to cities.

Input: An integer n (number of cities) and a 2D array roads where roads[i] = [ai, bi] represents a bidirectional road between cities ai and bi.

Output: Return the maximum possible total importance of all roads after optimal value assignment.

Input & Output

example_1.py โ€” Basic Linear Chain
$ Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
โ€บ Output: 43
๐Ÿ’ก Note: Cities have degrees: [2,3,4,2,1]. Sorted by degree: [4,0,3,1,2]. Assign values [1,2,3,4,5] respectively. City degrees: 4โ†’1, 0โ†’2, 3โ†’3, 1โ†’4, 2โ†’5. Total: (2+4)+(4+5)+(5+3)+(2+5)+(4+3)+(5+1) = 43
example_2.py โ€” Simple Triangle
$ Input: n = 3, roads = [[0,1],[1,2],[2,0]]
โ€บ Output: 12
๐Ÿ’ก Note: All cities have degree 2, so any assignment of [1,2,3] gives the same result. Each road contributes the sum of two different values, total = (1+2)+(2+3)+(3+1) = 12
example_3.py โ€” Star Graph
$ Input: n = 4, roads = [[0,1],[0,2],[0,3]]
โ€บ Output: 16
๐Ÿ’ก Note: City 0 has degree 3 (hub), others have degree 1. Assign highest value 4 to city 0, values [1,2,3] to others. Total = (4+1)+(4+2)+(4+3) = 16

Constraints

  • 2 โ‰ค n โ‰ค 5 ร— 104
  • 1 โ‰ค roads.length โ‰ค 5 ร— 104
  • roads[i].length == 2
  • 0 โ‰ค ai, bi โ‰ค n - 1
  • ai โ‰  bi
  • No duplicate roads

Visualization

Tap to expand
HUBVIP Level: 5City AVIP: 2City BVIP: 3City CVIP: 1City DVIP: 4Flight Value: 2+5=7Flight Value: 3+5=8Flight Value: 1+5=6Flight Value: 4+5=9Total Network Value7 + 8 + 6 + 9 = 30
Understanding the Visualization
1
Count Flight Connections
Count how many flights each airport handles (degree of each city)
2
Identify Hub Airports
Sort airports by their flight volume - busiest hubs first
3
Assign VIP Levels
Give highest VIP levels to the busiest hubs since they affect the most flights
4
Calculate Network Value
Sum up the total value across all flight routes
Key Takeaway
๐ŸŽฏ Key Insight: Assign highest importance values to the most connected cities (highest degree) because they contribute to the most roads, maximizing total importance.
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
78.6K Views
Medium Frequency
~18 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen