#1615
Medium Algorithms Maximal network rank
Graph Theory
65.9% acceptance
Feb 25, 2026
2446
393
There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
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.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn maximal_network_rank(n: i32, roads: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let mut degree = vec![0i32; n];
let mut connected: HashSet<(i32, i32)> = HashSet::new();
for r in &roads {
degree[r[0] as usize] += 1;
degree[r[1] as usize] += 1;
let a = r[0].min(r[1]);
let b = r[0].max(r[1]);
connected.insert((a, b));
}
let mut ans = 0;
for i in 0..n {
for j in (i+1)..n {
let rank = degree[i] + degree[j]
- if connected.contains(&(i as i32, j as i32)) { 1 } else { 0 };
ans = ans.max(rank);
}
}
ans
}
}