|
| 1 | +// Time: O(nlogn) ~ O(n^2) |
| 2 | +// Space: O(m + n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int maximalNetworkRank(int n, vector<vector<int>>& roads) { |
| 7 | + vector<int> degree(n); |
| 8 | + unordered_map<int, unordered_set<int>> adj; |
| 9 | + for (const auto& road : roads) { |
| 10 | + ++degree[road[0]]; |
| 11 | + ++degree[road[1]]; |
| 12 | + adj[road[0]].emplace(road[1]); |
| 13 | + adj[road[1]].emplace(road[0]); |
| 14 | + } |
| 15 | + vector<int> sorted_idx(n); |
| 16 | + iota(begin(sorted_idx), end(sorted_idx), 0); |
| 17 | + sort(begin(sorted_idx), end(sorted_idx), |
| 18 | + [°ree](const auto& a, const auto& b) { |
| 19 | + return degree[a] > degree[b]; |
| 20 | + }); |
| 21 | + int m = 2; |
| 22 | + for (; m < n; ++m) { |
| 23 | + if (degree[sorted_idx[m]] != degree[sorted_idx[1]]) { |
| 24 | + break; |
| 25 | + } |
| 26 | + } |
| 27 | + int result = degree[sorted_idx[0]] + degree[sorted_idx[1]] - 1; |
| 28 | + for (int i = 0; i < m - 1; ++i) { |
| 29 | + for (int j = i + 1; j < m; ++j) { |
| 30 | + if (degree[sorted_idx[i]] + degree[sorted_idx[j]] - int(adj.count(sorted_idx[i]) && adj[sorted_idx[i]].count(sorted_idx[j])) > result) { |
| 31 | + return degree[sorted_idx[i]] + degree[sorted_idx[j]] - int(adj.count(sorted_idx[i]) && adj[sorted_idx[i]].count(sorted_idx[j])); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + return result; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +// Time: O(n^2) |
| 40 | +// Space: O(m + n) |
| 41 | +class Solution2 { |
| 42 | +public: |
| 43 | + int maximalNetworkRank(int n, vector<vector<int>>& roads) { |
| 44 | + vector<int> degree(n); |
| 45 | + unordered_map<int, unordered_set<int>> adj; |
| 46 | + for (const auto& road : roads) { |
| 47 | + ++degree[road[0]]; |
| 48 | + ++degree[road[1]]; |
| 49 | + adj[road[0]].emplace(road[1]); |
| 50 | + adj[road[1]].emplace(road[0]); |
| 51 | + } |
| 52 | + int result = 0; |
| 53 | + for (int i = 0; i < n - 1; ++i) { |
| 54 | + for (int j = i + 1; j < n; ++j) { |
| 55 | + result = max(result, degree[i] + degree[j] - int(adj.count(i) && adj[i].count(j))); |
| 56 | + } |
| 57 | + } |
| 58 | + return result; |
| 59 | + } |
| 60 | +}; |
0 commit comments