Problem Description
Given n cities and an array of roads connecting pairs of these cities, the task is to determine the maximal network rank of the infrastructure. The network rank for a pair of cities is defined as the total number of roads directly connected to either city, counting a road that connects the two cities only once. The solution should return the maximum network rank considering all pairs of distinct cities.
Key Insights
- Use an array to count the number of roads connected to each city.
- Use a set (or equivalent) to record directly connected city pairs, so you can efficiently check if two cities have a direct road.
- Iterate through each distinct pair of cities to compute their network rank by summing their road counts and subtracting one if they are directly connected.
- Since n is at most 100, using a double loop over city pairs (O(n²)) is efficient enough.
Space and Time Complexity
Time Complexity: O(n²)
Space Complexity: O(n + m) where m is the number of roads (for storing connection information)
Solution
We first count the number of roads attached to each city. Meanwhile, we store each road connection in a set to quickly check if a pair of cities is directly connected. Then, we iterate over every possible pair of cities. For each pair, we calculate the network rank as the sum of their road counts and subtract one if they are directly connected. This method ensures we properly consider the shared road only once. We keep track of the maximum network rank found and return it.