|
| 1 | +/** |
| 2 | + * 1615. Maximal Network Rank |
| 3 | + * https://leetcode.com/problems/maximal-network-rank/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an infrastructure of n cities with some number of roads connecting these cities. |
| 7 | + * Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. |
| 8 | + * |
| 9 | + * The network rank of two different cities is defined as the total number of directly connected |
| 10 | + * roads to either city. If a road is directly connected to both cities, it is only counted once. |
| 11 | + * |
| 12 | + * The maximal network rank of the infrastructure is the maximum network rank of all pairs of |
| 13 | + * different cities. |
| 14 | + * |
| 15 | + * Given the integer n and the array roads, return the maximal network rank of the entire |
| 16 | + * infrastructure. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} n |
| 21 | + * @param {number[][]} roads |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var maximalNetworkRank = function(n, citiesConnections) { |
| 25 | + const cityRoadCounts = new Array(n).fill(0); |
| 26 | + const directConnections = new Set(); |
| 27 | + |
| 28 | + for (const [cityA, cityB] of citiesConnections) { |
| 29 | + cityRoadCounts[cityA]++; |
| 30 | + cityRoadCounts[cityB]++; |
| 31 | + directConnections.add(`${Math.min(cityA, cityB)}-${Math.max(cityA, cityB)}`); |
| 32 | + } |
| 33 | + |
| 34 | + let maxNetworkRank = 0; |
| 35 | + |
| 36 | + for (let cityA = 0; cityA < n; cityA++) { |
| 37 | + for (let cityB = cityA + 1; cityB < n; cityB++) { |
| 38 | + let networkRank = cityRoadCounts[cityA] + cityRoadCounts[cityB]; |
| 39 | + if (directConnections.has(`${cityA}-${cityB}`) |
| 40 | + || directConnections.has(`${cityB}-${cityA}`)) { |
| 41 | + networkRank--; |
| 42 | + } |
| 43 | + maxNetworkRank = Math.max(maxNetworkRank, networkRank); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return maxNetworkRank; |
| 48 | +}; |
0 commit comments