Maximum Total Importance of Roads LeetCode solution in JavaScript

1
var maximumImportance = function (n, roads) {
2
const connectionCount = Array(n).fill(0);
3

4
// Count the connections from each city
5
// e.g. the 0th city's count will be stored at index zero in the array
6
for (let [cityTo, cityFrom] of roads) {
7
connectionCount[cityTo]++;
8
connectionCount[cityFrom]++;
9
}
10

11
let cityToConnectionCount = [];
12
for (let city = 0; city < n; city++) {
13
cityToConnectionCount.push([city, connectionCount[city]]); // Store the [city, numberOfConnections]
14
}
15

16
// Created new array(sortedCities) for readability
17
// sort by number of connections, the city with the greatest number of connections should be
18
const sortedCities = cityToConnectionCount.sort((a, b) => b[1] - a[1]);
19
// the city with the greatest importance
20

21
const values = Array(n).fill(0);
22
let importance = n;
23
for (let i = 0; i < sortedCities.length; i++) {
24
const [city, connectionCount] = cityToConnectionCount[i];
25
values[city] = importance; // City at the 0th position array is should be the city with the greatest importance
26
importance--;
27
}
28

29
// Sum the importance of each city, toCity => fromCity
30
let res = 0;
31
for (let [to, from] of roads) {
32
res += values[to] + values[from];
33
}
34

35
return res;
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0