Approach
Breadth-first search
For Maximum Employees to Be Invited to a Meeting, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 77 lines of C++ from the credited upstream file 2127.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 8 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1enum class State { kInit, kVisiting, kVisited };2 3class Solution {4 public:5 int maximumInvitations(vector<int>& favorite) {6 const int n = favorite.size();7 int sumComponentsLength = 0; 8 vector<vector<int>> graph(n);9 vector<int> inDegrees(n);10 vector<int> maxChainLength(n, 1);11 queue<int> q;12 13 14 for (int i = 0; i < n; ++i) {15 graph[i].push_back(favorite[i]);16 ++inDegrees[favorite[i]];17 }18 19 20 for (int i = 0; i < n; ++i)21 if (inDegrees[i] == 0)22 q.push(i);23 24 while (!q.empty()) {25 const int u = q.front();26 q.pop();27 for (const int v : graph[u]) {28 if (--inDegrees[v] == 0)29 q.push(v);30 maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]);31 }32 }33 34 for (int i = 0; i < n; ++i)35 if (favorite[favorite[i]] == i)36 37 sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]];38 39 int maxCycleLength = 0; 40 vector<int> parent(n, -1);41 vector<bool> seen(n);42 vector<State> states(n);43 44 for (int i = 0; i < n; ++i)45 if (!seen[i])46 findCycle(graph, i, parent, seen, states, maxCycleLength);47 48 return max(sumComponentsLength / 2, maxCycleLength);49 }50 51 private:52 void findCycle(const vector<vector<int>>& graph, int u, vector<int>& parent,53 vector<bool>& seen, vector<State>& states,54 int& maxCycleLength) {55 seen[u] = true;56 states[u] = State::kVisiting;57 58 for (const int v : graph[u]) {59 if (!seen[v]) {60 parent[v] = u;61 findCycle(graph, v, parent, seen, states, maxCycleLength);62 } else if (states[v] == State::kVisiting) {63 64 int curr = u;65 int cycleLength = 1;66 while (curr != v) {67 curr = parent[curr];68 ++cycleLength;69 }70 maxCycleLength = max(maxCycleLength, cycleLength);71 }72 }73 74 states[u] = State::kVisited;75 }76};77