Maximum Employees to Be Invited to a Meeting

Updated on 16 June, 2025
Maximum Employees to Be Invited to a Meeting header image

Problem Statement

In this problem, a company is planning to host a meeting with a specific seating arrangement around a circular table. There are n employees, each labeled from 0 to n - 1. Every employee has a favorite person they want to sit next to, and will only attend the meeting if this condition is met. The desired seating partner for an employee is expressed using a 0-indexed integer array favorite, where favorite[i] indicates the favorite person of the i-th employee. Notably, no employee selects themselves as their favorite. The goal is to find the maximum number of employees that can be accommodated at the table in such a way that each attendee is seated next to their favorite peer.

Examples

Example 1

Input:

favorite = [2,2,1,2]

Output:

3

Explanation:

The company can invite employees 0, 1, and 2, and seat them at the round table.
Employee 2 cannot sit beside employees 0, 1, and 3 simultaneously.
The company can also invite employees 1, 2, and 3. In both cases, the answer is 3.

Example 2

Input:

favorite = [1,2,0]

Output:

3

Explanation:

This is a simple cycle: 0 → 1 → 2 → 0.
Everyone can sit next to their favorite person.

Example 3

Input:

favorite = [3,0,1,4,1]

Output:

4

Explanation:

The company can invite employees 0, 1, 3, and 4.
Employee 2 cannot be invited because their favorite (employee 1) already has both neighbors occupied.

Constraints

  • n == favorite.length
  • 2 <= n <= 10^5
  • 0 <= favorite[i] <= n - 1
  • favorite[i] != i

Approach and Intuition

The challenge is to find a valid circular arrangement where each person is next to their favorite. This can be modeled using directed graphs:

  1. Cycle Detection:

    • If there's a cycle (e.g., 0 → 1 → 2 → 0), all employees in that cycle can be invited.
    • Track the size of the largest cycle found.
  2. Mutual Pairs with Chains:

    • If favorite[a] == b and favorite[b] == a, it’s a mutual pair.
    • For these pairs, include the longest incoming chains to both a and b.
  3. Graph Traversal:

    • Build a graph where each node points to its favorite.
    • Use DFS to compute longest paths into each node (for mutual pairs).
    • Track visited nodes to avoid double counting.
  4. Final Result:

    • Take the maximum of:

      • The largest simple cycle.
      • The total sum from all mutual pairs and their incoming chains.

This approach ensures an optimal solution that works within the constraint limits by reducing the problem to efficient graph traversal and cycle/chain detection.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maxInvitations(vector<int>& favorites) {
        int size = favorites.size();
        vector<int> inDeg(size, 0);

        // Compute in-degree for nodes
        for (int i = 0; i < size; ++i) {
            inDeg[favorites[i]]++;
        }

        // Implementing topological sort to identify and remove acyclic nodes
        queue<int> processingQueue;
        for (int i = 0; i < size; ++i) {
            if (inDeg[i] == 0) {
                processingQueue.push(i);
            }
        }

        vector<int> nodeDepth(size, 1);  // Storing depth of each node
        while (!processingQueue.empty()) {
            int currentNode = processingQueue.front();
            processingQueue.pop();
            int nextNode = favorites[currentNode];
            nodeDepth[nextNode] = max(nodeDepth[nextNode], nodeDepth[currentNode] + 1);
            if (--inDeg[nextNode] == 0) {
                processingQueue.push(nextNode);
            }
        }

        int maxCycleLength = 0;
        int pairInvitations = 0;

        // Identifying and processing cycles
        for (int i = 0; i < size; ++i) {
            if (inDeg[i] == 0) continue;  // Skip nodes already in acyclic parts

            int length = 0;
            int current = i;
            while (inDeg[current] != 0) {
                inDeg[current] = 0;  // Mark as processed
                length++;
                current = favorites[current];
            }

            if (length == 2) {
                // Calculate total depth for each node in the 2-cycle
                pairInvitations += nodeDepth[i] + nodeDepth[favorites[i]];
            } else {
                maxCycleLength = max(maxCycleLength, length);
            }
        }

        return max(maxCycleLength, pairInvitations);
    }
};

The solution is designed to find the maximum number of employees that can be invited to a meeting, based on their interdependent favorite connections, using C++.

  • First, initialize the in-degree vector to understand the number of direct invitations pointed towards each employee.
  • Employ the topological sort methodology to process nodes starting from those with zero in-degrees (no direct invitations), effectively handling and removing any acyclic node dependencies.
  • Use a queue to manage the nodes for this processing, enhancing each connected node's depth based on its predecessor, until no nodes with zero in-degree remain.
  • To evaluate the mutually inviting pairs and longer cycles within the graph, you iterate through all nodes still marked with in-degrees and calculate the total cycle lengths.
  • Special attention is given to pairs (cycles of length two), where the sum of depths between the dyadic pairs are calculated for optimal invitation planning.
  • Finally, determine the maximum value between the longest detected cycle and the total invitation count possible via dyadic pairs.

This ensures a solution that balances computational efficiency with clear logistical understanding of complex, cyclic employee invitations. The same approach can be applied generally to similar graph-based relational problems where directional and cyclic relationship patterns need to be efficiently analyzed and distilled into actionable insights.

java
class PartyInvitations {

    public int maxGuests(int[] favs) {
        int count = favs.length;
        int[] invites = new int[count];

        // Calculate each person's incoming invites
        for (int i = 0; i < count; ++i) {
            invites[favs[i]]++;
        }

        // Prepare to process invites with no incoming
        Queue<Integer> processQueue = new LinkedList<>();
        for (int i = 0; i < count; ++i) {
            if (invites[i] == 0) {
                processQueue.offer(i);
            }
        }

        int[] reach = new int[count]; // reachability depth
        Arrays.fill(reach, 1);

        // Process with topological sort
        while (!processQueue.isEmpty()) {
            int current = processQueue.poll();
            int next = favs[current];
            reach[next] = Math.max(reach[next], reach[current] + 1);
            if (--invites[next] == 0) {
                processQueue.offer(next);
            }
        }

        int maxCycle = 0;
        int twoNodeCycleSum = 0;

        // Find cycles
        for (int i = 0; i < count; ++i) {
            if (invites[i] == 0) continue;

            int cycleSize = 0;
            int current = i;
            while (invites[current] != 0) {
                // Check off this person as visited
                invites[current] = 0;
                cycleSize++;
                current = favs[current];
            }

            if (cycleSize == 2) {
                // Special case for 2-node cycles
                twoNodeCycleSum += reach[i] + reach[favs[i]];
            } else {
                maxCycle = Math.max(maxCycle, cycleSize);
            }
        }

        return Math.max(maxCycle, twoNodeCycleSum);
    }
}

The Java function maxGuests in the PartyInvitations class addresses the issue of determining the maximum number of employees that can be invited to a meeting, assuming that each employee prefers to go with one specific colleague indicated in the array favs. The function uses a graph theory approach, specifically focusing on processing cycles and components within a directed graph where nodes are employees and edges indicate preference.

  • The function begins by initializing an array invites to count incoming edges (preferences) for each employee. It processes each preference to update this count.
  • Next, a queue processQueue is utilized to manage and explore nodes (employees) with no incoming preferences using a topological sorting-like approach.
  • An array reach is then employed to track the reachability or the depth of invite chains starting from each node.
  • By traversing and updating the reach values based on the topological sort results, the function prepares to handle cycles and interconnected components of the employee preference graph.
  • The actual cycle processing is done in a separate loop, where each cycle is identified and tracked. Specifically, it distinguishes between cycles of size two (treated as a special case) and larger cycles.
  • The function sums up the reachability results for two-node cycles to handle cases where employees prefer each other, potentially forming multi-node interconnected components.
  • Finally, it calculates the maximum value between the largest found cycle and the sum of interconnected two-node cycles, which is the answer to the maximum number of guests that can be invited.

This approach efficiently handles both linear chains of preferences and complex cyclic dependencies among employees.

python
class Solution:
    def maxInvites(self, favs: List[int]) -> int:
        size = len(favs)
        in_deg = [0] * size

        # Increment in-degrees based on favorites
        for idx in range(size):
            in_deg[favs[idx]] += 1

        # Building zero in-degree queue
        queue = deque()
        for idx in range(size):
            if in_deg[idx] == 0:
                queue.append(idx)
        node_depth = [1] * size  # stores the depth of each invitation chain

        while queue:
            current = queue.popleft()
            next_invite = favs[current]
            node_depth[next_invite] = max(node_depth[next_invite], node_depth[current] + 1)
            in_deg[next_invite] -= 1
            if in_deg[next_invite] == 0:
                queue.append(next_invite)

        max_cycle = 0
        double_cycle_value = 0

        # Processing cycles to calculate maximum invites
        for idx in range(size):
            if in_deg[idx] == 0:
                continue

            cycle_size = 0
            start = idx
            while in_deg[start] > 0:
                in_deg[start] = 0  # Mark as processed
                cycle_size += 1
                start = favs[start]

            if cycle_size == 2:
                # Calculate combined depth for 2-node cycles
                double_cycle_value += node_depth[idx] + node_depth[favs[idx]]
            else:
                max_cycle = max(max_cycle, cycle_size)

        return max(max_cycle, double_cycle_value)

The task centers around finding the maximum number of employees that can be invited to a meeting using a specific strategy based on their favorite invitations. The code provided implements this in Python using a graph-based approach where employees' favorite choices create a directed graph.

Here's a breakdown of the implementation steps:

  1. Initialize the degree of each node (employees) to zero to keep track of incoming edges.
  2. Construct an in-degree array by iterating over each employee's favorite and incrementing the corresponding favorite's in-degree.
  3. Establish a queue for nodes with zero in-degrees to handle the first layer of employees who aren't anyone else's favorite.
  4. Implement a breadth-first search (BFS) starting from these initial nodes. During BFS processing, update in-degrees and employ a node depth array to track the longest chain of invitations that terminate at each employee.
  5. Search for cycles within the graph since a cycle indicates a possibility of inviting more employees continuously. Special attention is given to two-node cycles which represent a mutual favorite relationship.
  6. Calculate the maximum number of invitations by considering the longest single-cycle and the combined lengths from the two-node cycles.

This algorithm aims to:

  • Identify all components in the graph, namely straightforward invitation chains and closed loops (or cycles).
  • Utilize queue-based BFS to efficiently process each possible starting point in chains.
  • Use a two-fold approach to handle different types of cycles, particularly distinguishing between simple cycles and two-node (mutual) cycles for optimized invitation planning.

This process ensures a comprehensive strategy to maximize the meeting invitees by leveraging relationships between employees' preferences within a well-defined graph structure.

Comments

No comments yet.