Maximal Network Rank - Problem
Imagine you're a city infrastructure analyst tasked with evaluating road network connectivity between cities. You have n cities connected by bidirectional roads, and you need to find the maximal network rank - a measure of how well-connected any pair of cities can be.
The network rank of two different cities is calculated as:
- Count all roads directly connected to the first city
- Count all roads directly connected to the second city
- Add these counts together
- Important: If there's a direct road between these two cities, count it only once (not twice)
Your goal is to find the maximum possible network rank among all pairs of different 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 maximal network rank as an integer.
Input & Output
example_1.py โ Python
$
Input:
n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
โบ
Output:
4
๐ก Note:
The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. Note that the road between 0 and 1 is only counted once.
example_2.py โ Python
$
Input:
n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
โบ
Output:
5
๐ก Note:
There are 5 roads that are connected to cities 1 or 2.
example_3.py โ Python
$
Input:
n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
โบ
Output:
5
๐ก Note:
The network rank of 2 and 5 is 5. Note that all the cities do not have to be connected.
Constraints
- 2 โค n โค 100
- 0 โค roads.length โค n * (n-1) / 2
- roads[i].length == 2
- 0 โค ai, bi โค n-1
- ai != bi
- Each road connects two different cities
- There are no repeated roads
Visualization
Tap to expand
Understanding the Visualization
1
Build Network
Create the road network between cities
2
Count Connections
For each city, count how many roads it has
3
Check Pairs
For each pair, add their road counts
4
Avoid Double Counting
If cities are directly connected, subtract 1
5
Find Maximum
Track the highest network rank found
Key Takeaway
๐ฏ Key Insight: We only need to store degree counts and check direct connections - no need for complex graph traversal!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code