[LeetCode 2410] Maximum Matching of Players With Trainers
LeetCode 2410 (Java)
[Maximum Matching of Players With Trainers] 문제 풀이
[LeetCode 2410] Maximum Matching of Players With Trainers
Description
You are given a 0-indexed integer array players, where players[i] represents the ability of the i^th player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the j^th trainer.
The i^th player can match with the j^th trainer if the player’s ability is less than or equal to the trainer’s training capacity. Additionally, the i^th player can be matched with at most one trainer, and the j^th trainer can be matched with at most one player.
Return the maximum number of matchings between players and trainers that satisfy these conditions.
Example 1
- Input: players = [4,7,9], trainers = [8,2,5,8]
- Output: 2
- Explanation:
- One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 <= 8.
- players[1] can be matched with trainers[3] since 7 <= 8.
- It can be proven that 2 is the maximum number of matchings that can be formed.
- One of the ways we can form two matchings is as follows:
Example 2
- Input: players = [1,1,1], trainers = [10]
- Output: 1
- Explanation:
- The trainer can be matched with any of the 3 players.
- Each player can only be matched with one trainer, so the maximum answer is 1.
Constraints
1 <= players.length, trainers.length <= 10^51 <= players[i], trainers[j] <= 10^9
Hint
Hint 1
Sort both the arrays.
Hint 2
Construct the matching greedily.
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int matchPlayersAndTrainers(int[] players, int[] trainers) {
Arrays.sort(players);
Arrays.sort(trainers);
int m = players.length, n = trainers.length;
for (int i = 0, j = 0; i < m; ++i, ++j) {
while (j < n && trainers[j] < players[i]) {
++j;
}
if (j == n) {
return i;
}
}
return m;
}
}
| Runtime | Memory |
|---|---|
| 25 ms | 58.1 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int matchPlayersAndTrainers(int[] p, int[] t) {
int i=0;
Arrays.sort(p);
Arrays.sort(t);
int j=0; int count=0;
while(i<p.length && j<t.length){
if(p[i]<=t[j]){
count++;
i++;
j++;
}else{
j++;
}
}
return count;
}
}
Reference
- https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/?envType=daily-question&envId=2025-07-13
This post is licensed under CC BY 4.0 by the author.
