LeetCode 1820. Maximum Number of Accepted Invitations Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1820. Maximum Number of Accepted Invitations

Description

There are m boys and n girls in a class attending an upcoming party.

You are given an m x n integer matrix grid, where grid[i][j] equals 0 or 1. If grid[i][j] == 1, then that means the ith boy can invite the jth girl to the party. A boy can invite at most one girl, and a girl can accept at most one invitation from a boy.

Return the maximum possible number of accepted invitations.

 

Example 1:

Input: grid = [[1,1,1],
               [1,0,1],
               [0,0,1]]
Output: 3
Explanation: The invitations are sent as follows:
- The 1st boy invites the 2nd girl.
- The 2nd boy invites the 1st girl.
- The 3rd boy invites the 3rd girl.

Example 2:

Input: grid = [[1,0,1,0],
               [1,0,0,0],
               [0,0,1,0],
               [1,1,1,0]]
Output: 3
Explanation: The invitations are sent as follows:
-The 1st boy invites the 3rd girl.
-The 2nd boy invites the 1st girl.
-The 3rd boy invites no one.
-The 4th boy invites the 2nd girl.

 

Constraints:

  • grid.length == m
  • grid[i].length == n
  • 1 <= m, n <= 200
  • grid[i][j] is either 0 or 1.

Solutions

Solution 1: Hungarian Algorithm

This problem belongs to the maximum matching problem of bipartite graphs, which is suitable for solving with the Hungarian algorithm.

The core idea of the Hungarian algorithm is to continuously start from unmatched points, look for augmenting paths, and stop when there are no augmenting paths. This gives the maximum match.

The time complexity is O(m × n).

PythonJavaC++Go
class Solution: def maximumInvitations(self, grid: List[List[int]]) -> int: def find(i): for j, v in enumerate(grid[i]): if v and j not in vis: vis.add(j) if match[j] == -1 or find(match[j]): match[j] = i return True return False m, n = len(grid), len(grid[0]) match = [-1] * n ans = 0 for i in range(m): vis = set() ans += find(i) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !