The Maximal Network Rank problem gives you an integer n (number of cities) and an array of roads connecting them. The "network rank" of any two distinct cities is the total number of roads directly connected to either city. If a road directly connects the two cities, it should only be counted once. Your goal is to find the maximum network rank out of all possible pairs of cities.
This is a straightforward Graph problem. Interviewers use it to verify that a candidate understands basic graph properties like nodes, edges, and degrees. It is an excellent test of whether a candidate can build an adjacency list or matrix and accurately handle the "intersection" logic (avoiding double-counting a shared edge).
This utilizes Graph Degree Counting and Nested Iteration. Because n is small (typically up to 100), an traversal of all city pairs is perfectly optimal.
(i, j). The network rank is degree[i] + degree[j]. If the adjacency matrix indicates they are connected, subtract 1 to avoid double-counting. Track the global maximum.4 cities, roads: [[0,1], [0,3], [1,2], [1,3]].
degree[0] + degree[1] = . They are connected, so subtract 1. Rank = 4.degree[1] + degree[3] = . They are connected. Subtract 1. Rank = 4.degree[0] + degree[2] = . They are NOT connected. Subtract 0. Rank = 3.
The maximum network rank is 4.A common error is trying to find the two cities with the absolute highest degrees and assuming their combined rank is the answer. This greedy assumption fails! Two cities with slightly lower degrees that are not connected might yield a higher network rank than two top-degree cities that are connected. You must check every pair. Another mistake is using a slow adjacency list lookup instead of a fast adjacency matrix, causing unnecessary slowdowns.
For the Maximal Network Rank coding problem, immediately declare an int[] counts for the node degrees and a boolean[][] connected for the adjacency matrix. This setup takes 5 lines of code and reduces the core logic to a trivial double-for-loop. It is a highly reliable template for dense graph comparison problems.