Maximum Total Importance of Roads - Problem

You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.

You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.

Return the maximum total importance of all roads possible after assigning the values optimally.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
Output: 43
💡 Note: Count degrees: City 0(2), 1(3), 2(4), 3(2), 4(1). Assign values: 2→5, 1→4, 0→3, 3→2, 4→1. Total importance = (3+4)+(4+5)+(5+2)+(3+5)+(4+2)+(5+1) = 43
Example 2 — Linear Chain
$ Input: n = 4, roads = [[0,1],[1,2],[2,3]]
Output: 17
💡 Note: Degrees: 0(1), 1(2), 2(2), 3(1). Assign: 1→4, 2→3, 0→2, 3→1. Total = (2+4)+(4+3)+(3+1) = 17
Example 3 — Single Road
$ Input: n = 2, roads = [[0,1]]
Output: 5
💡 Note: Two cities with one road. Assign values 2 and 1. Total importance = 2 + 1 = 5

Constraints

  • 2 ≤ n ≤ 5 × 104
  • 1 ≤ roads.length ≤ 5 × 104
  • roads[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi
  • There are no duplicate roads

Visualization

Tap to expand
Maximum Total Importance of Roads INPUT Graph with n=5 cities 0 1 2 3 4 n = 5 roads = [[0,1],[1,2],[2,3], [0,2],[1,3],[2,4]] ALGORITHM STEPS 1 Count Degrees Count connections per city City: 0 1 2 3 4 Degree: 2 3 4 2 1 2 Sort by Degree Descending order [2(4), 1(3), 0(2), 3(2), 4(1)] 3 Assign Values Highest to most connected City 2 --> 5, City 1 --> 4 City 0 --> 3, City 3 --> 2, City 4 --> 1 4 Calculate Total Sum: degree[i] * value[i] 4*5 + 3*4 + 2*3 + 2*2 + 1*1 = 43 FINAL RESULT Optimally Assigned Values 0 v=3 1 v=4 2 v=5 3 v=2 4 v=1 OUTPUT 43 Key Insight: Cities with more roads (higher degree) contribute their value more times to the total. By assigning the highest values to cities with the most connections, we maximize the sum. Total = Sum of (degree[i] * assigned_value[i]) for all cities. Time: O(n log n), Space: O(n) TutorialsPoint - Maximum Total Importance of Roads | Greedy by Degree Approach
Asked in
Google 15 Microsoft 12 Amazon 8
18.5K Views
Medium Frequency
~25 min Avg. Time
890 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