Maximal Network Rank Problem
Description
LeetCode Problem 1615.
There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a_i, b_i] indicates that there is a bidirectional road between cities a_i and b_i.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
Example 1:

Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
Output: 4
Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
Example 2:

Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
Output: 5
Explanation: There are 5 roads that are connected to cities 1 or 2.
Example 3:
Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
Output: 5
Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
Constraints:
2 <= n <= 1000 <= roads.length <= n * (n - 1) / 2roads[i].length == 20 <= a_i, b_i <= n-1a_i != b_i- Each pair of cities has at most one road connecting them.
Solution
Approach: Degrees of Every Pair
The network rank of two cities a and b is the number of roads touching a plus the number touching b, minus 1 if there is a road between them, because that road was counted twice.
So first compute each city's degree (its number of roads) and record which pairs are connected in an n x n table. Then try every pair a < b and take the largest degree[a] + degree[b] - connected[a][b].
Just picking the two cities with the highest degrees is not enough: if they are connected, another pair with the same degree sum but no road between them is better by 1. With n <= 100, checking all pairs is cheap anyway.
As example 3 shows, the two cities don't need to be connected, or even in the same part of the network.
Complexity: O(n2 + m) time and O(n2) extra space, where m is the number of roads.
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
degree = [0] * n
connected = [[False] * n for _ in range(n)]
for a, b in roads:
degree[a] += 1
degree[b] += 1
connected[a][b] = connected[b][a] = True
ans = 0
for a in range(n):
for b in range(a + 1, n):
# A road between a and b touches both cities but counts once.
ans = max(ans, degree[a] + degree[b] - connected[a][b])
return ans