- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 72 lines of C++ from the credited upstream file 1615.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maximalNetworkRank(int n, vector<vector<int>>& roads) {4 vector<int> degrees(n);5 6 for (const vector<int>& road : roads) {7 const int u = road[0];8 const int v = road[1];9 ++degrees[u];10 ++degrees[v];11 }12 13 14 int maxDegree1 = 0;15 int maxDegree2 = 0;16 for (const int degree : degrees) {17 if (degree > maxDegree1) {18 maxDegree2 = maxDegree1;19 maxDegree1 = degree;20 } else if (degree > maxDegree2) {21 maxDegree2 = degree;22 }23 }24 25 26 27 int countMaxDegree1 = 0;28 int countMaxDegree2 = 0;29 for (const int degree : degrees)30 if (degree == maxDegree1)31 ++countMaxDegree1;32 else if (degree == maxDegree2)33 ++countMaxDegree2;34 35 if (countMaxDegree1 == 1) {36 37 38 39 40 const int edgeCount =41 getEdgeCount(roads, degrees, maxDegree1, maxDegree2) +42 getEdgeCount(roads, degrees, maxDegree2, maxDegree1);43 return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0);44 } else {45 46 47 48 49 const int edgeCount =50 getEdgeCount(roads, degrees, maxDegree1, maxDegree1);51 const int maxPossibleEdgeCount =52 countMaxDegree1 * (countMaxDegree1 - 1) / 2;53 return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0);54 }55 }56 57 private:58 59 60 int getEdgeCount(const vector<vector<int>>& roads, const vector<int>& degrees,61 int degreeU, int degreeV) {62 int edgeCount = 0;63 for (const vector<int>& road : roads) {64 const int u = road[0];65 const int v = road[1];66 if (degrees[u] == degreeU && degrees[v] == degreeV)67 ++edgeCount;68 }69 return edgeCount;70 }71};72