LeetCode 1820: Maximum Number of Accepted Invitations

Problem Description

Explanation:

To solve this problem, we can use the maximum matching algorithm on bipartite graphs. We can model the problem as a bipartite graph where nodes on one side represent boys and nodes on the other side represent girls. The edges between boys and girls represent whether they can accept an invitation from each other.

  1. Create a bipartite graph where boys are connected to girls if they can go together to an event.
  2. Use the Hopcroft-Karp algorithm to find the maximum matching in the bipartite graph.
  3. The maximum number of accepted invitations will be the size of the maximum matching.

Complexity Analysis:

  • The time complexity of the Hopcroft-Karp algorithm is O(sqrt(V) * E), where V is the number of vertices and E is the number of edges.
  • The space complexity is O(V + E).

:

Solutions

class Solution {
    public int maximumInvitations(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[] match = new int[n];
        Arrays.fill(match, -1);
        
        int count = 0;
        for (int i = 0; i < m; i++) {
            boolean[] visited = new boolean[n];
            if (dfs(grid, i, visited, match)) {
                count++;
            }
        }
        
        return count;
    }
    
    private boolean dfs(int[][] grid, int boy, boolean[] visited, int[] match) {
        int n = grid[0].length;
        for (int girl = 0; girl < n; girl++) {
            if (grid[boy][girl] == 1 && !visited[girl]) {
                visited[girl] = true;
                if (match[girl] == -1 || dfs(grid, match[girl], visited, match)) {
                    match[girl] = boy;
                    return true;
                }
            }
        }
        return false;
    }
}

Loading editor...