-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1820-maximum-number-of-accepted-invitations.js
More file actions
48 lines (42 loc) · 1.3 KB
/
1820-maximum-number-of-accepted-invitations.js
File metadata and controls
48 lines (42 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 1820. Maximum Number of Accepted Invitations
* https://leetcode.com/problems/maximum-number-of-accepted-invitations/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[][]} grid
* @return {number}
*/
var maximumInvitations = function(grid) {
const boyCount = grid.length;
const girlCount = grid[0].length;
const girlMatched = new Array(girlCount).fill(-1);
let result = 0;
for (let boy = 0; boy < boyCount; boy++) {
const visited = new Array(girlCount).fill(false);
if (findMatch(boy, visited)) {
result++;
}
}
return result;
function findMatch(boy, visited) {
for (let girl = 0; girl < girlCount; girl++) {
if (grid[boy][girl] && !visited[girl]) {
visited[girl] = true;
if (girlMatched[girl] === -1 || findMatch(girlMatched[girl], visited)) {
girlMatched[girl] = boy;
return true;
}
}
}
return false;
}
};