MediumArrayDepth-First SearchGraphMatrix

Maximum Number of Accepted Invitations

1 approach, code in every language

Problem description

There are m boys and n girls at a party, described by an m x n binary matrix grid. If grid[i][j] == 1, then boy i is allowed to invite girl j to dance; otherwise he cannot.

Each boy may invite at most one girl, and each girl may accept at most one invitation. You want to arrange the invitations so that as many dance pairs form as possible.

Return the maximum possible number of accepted invitations.

Example 1

Input: grid = [[1,1,1],[1,0,1],[0,0,1]]

Output: 3

Boy 0 invites girl 1, boy 1 invites girl 0, and boy 2 invites girl 2. All three invitations are accepted.

Example 2

Input: grid = [[1,0,1,0],[1,0,0,0],[0,0,1,0],[1,1,1,0]]

Output: 3

One optimal pairing is boy 0 -> girl 2, boy 1 -> girl 0, and boy 3 -> girl 1. Boy 2 shares girl 2 with boy 0, so only three matches are possible.

Constraints

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

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free