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 Java from the credited upstream file 2127.java.
- The implementation visibly relies on sequence storage, work queue.
- 7 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 State { INIT, VISITING, VISITED }2 3class Solution {4 public int maximumInvitations(int[] favorite) {5 final int n = favorite.length;6 int sumComponentsLength = 0; 7 List<Integer>[] graph = new List[n];8 int[] inDegrees = new int[n];9 int[] maxChainLength = new int[n];10 Arrays.fill(maxChainLength, 1);11 Arrays.setAll(graph, i -> new ArrayList<>());12 13 14 for (int i = 0; i < n; ++i) {15 graph[i].add(favorite[i]);16 ++inDegrees[favorite[i]];17 }18 19 20 Queue<Integer> q = IntStream.range(0, n)21 .filter(i -> inDegrees[i] == 0)22 .boxed()23 .collect(Collectors.toCollection(ArrayDeque::new));24 25 while (!q.isEmpty()) {26 final int u = q.poll();27 for (final int v : graph[u]) {28 if (--inDegrees[v] == 0)29 q.offer(v);30 maxChainLength[v] = Math.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[] parent = new int[n];40 Arrays.fill(parent, -1);41 boolean[] seen = new boolean[n];42 State[] states = new State[n];43 44 for (int i = 0; i < n; ++i)45 if (!seen[i])46 findCycle(graph, i, parent, seen, states);47 48 return Math.max(sumComponentsLength / 2, maxCycleLength);49 }50 51 private int maxCycleLength = 0; 52 53 private void findCycle(List<Integer>[] graph, int u, int[] parent, boolean[] seen,54 State[] states) {55 seen[u] = true;56 states[u] = State.VISITING;57 58 for (final int v : graph[u]) {59 if (!seen[v]) {60 parent[v] = u;61 findCycle(graph, v, parent, seen, states);62 } else if (states[v] == State.VISITING) {63 64 int curr = u;65 int cycleLength = 1;66 while (curr != v) {67 curr = parent[curr];68 ++cycleLength;69 }70 maxCycleLength = Math.max(maxCycleLength, cycleLength);71 }72 }73 74 states[u] = State.VISITED;75 }76}77