2410. Maximum Matching of Players With Trainers #1922
-
Topics: You are given a 0-indexed integer array The Return the maximum number of matchings between Example 1:
Example 2:
Constraints:
Note: This question is the same as 445: Assign Cookies. Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum number of matchings between players and trainers such that each player's ability is less than or equal to the trainer's capacity. Each player can match with at most one trainer, and each trainer can match with at most one player. Approach
Let's implement this solution in PHP: 2410. Maximum Matching of Players With Trainers <?php
/**
* @param Integer[] $players
* @param Integer[] $trainers
* @return Integer
*/
function matchPlayersAndTrainers($players, $trainers) {
sort($players);
sort($trainers);
$count = 0;
$i = 0;
$j = 0;
$n = count($players);
$m = count($trainers);
while ($i < $n && $j < $m) {
if ($players[$i] <= $trainers[$j]) {
$count++;
$i++;
$j++;
} else {
$j++;
}
}
return $count;
}
// Test cases
// Example 1
$players = array(4, 7, 9);
$trainers = array(8, 2, 5, 8);
echo matchPlayersAndTrainers($players, $trainers); // Output: 2
echo "\n";
// Example 2
$players = array(1, 1, 1);
$trainers = array(10);
echo matchPlayersAndTrainers($players, $trainers); // Output: 1
?> Explanation:
This approach efficiently maximizes the number of matchings by leveraging sorting and a greedy strategy, ensuring optimal performance with a time complexity dominated by the sorting steps: O(n log n + m log m), where n and m are the lengths of the |
Beta Was this translation helpful? Give feedback.
We need to find the maximum number of matchings between players and trainers such that each player's ability is less than or equal to the trainer's capacity. Each player can match with at most one trainer, and each trainer can match with at most one player.
Approach
players
andtrainers
arrays in ascending order. Sorting helps in efficiently applying a greedy strategy to find the maximum matchings.