LeetCode 1615: Maximal Network Rank

Graph

Problem Description

Explanation:

To solve this problem, we need to calculate the network rank of each pair of cities and find the maximal network rank among them. The network rank of two cities is the count of roads directly connected to either city, counting a road connecting both cities only once.

We can iterate through all pairs of cities and calculate the total number of roads directly connected to either city in the pair. The maximal network rank will be the maximum value obtained from these calculations.

Algorithm:

  1. Create a 2D array adj of size n x n to represent the roads directly connecting cities.
  2. Initialize a variable maxRank to store the maximal network rank and set it to 0.
  3. Iterate through all pairs of cities (i, j) where i < j:
    • Calculate the network rank of cities i and j by summing the number of roads directly connecting to either city (adj[i][k] + adj[j][k]) and subtracting 1 if the road directly connects both cities (adj[i][j] == 1).
    • Update maxRank if the current network rank is greater than maxRank.
  4. Return maxRank as the maximal network rank.

Time Complexity:

The time complexity of this approach is O(n^2) where n is the number of cities.

Space Complexity:

The space complexity is O(n^2) to store the adjacency matrix.

:

Solutions

class Solution {
    public int maximalNetworkRank(int n, int[][] roads) {
        int maxRank = 0;
        int[][] adj = new int[n][n];
        
        for (int[] road : roads) {
            int city1 = road[0];
            int city2 = road[1];
            adj[city1][city2] = 1;
            adj[city2][city1] = 1;
        }
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int rank = 0;
                for (int k = 0; k < n; k++) {
                    rank += adj[i][k] + adj[j][k];
                }
                if (adj[i][j] == 1) {
                    rank--;
                }
                maxRank = Math.max(maxRank, rank);
            }
        }
        
        return maxRank;
    }
}

Loading editor...