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
Understanding the Visualization
1
Input
Cities 0-3 with roads [[0,1],[1,2],[2,3]]
2
Process
Count degrees and assign values by importance
3
Output
Maximum total importance of all roads
Key Takeaway
🎯 Key Insight: Cities with more roads contribute their value to more importance calculations, so assign highest values to highest-degree cities
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code