Maximum Matching of Players With Trainers Program
🔷 Problem Statement:
You are given two integer arrays:
players
→ each value represents the ability of a playertrainers
→ each value represents the training capacity of a trainer
A player can be matched with a trainer only if:
player’s ability <= trainer’s capacity
Each player can be matched with at most one trainer, and each trainer with at most one player.
Goal: Return the maximum number of matchings you can make.
Example:
players = [4, 7, 9]
trainers = [8, 2, 5, 8]
Output: 2
Explanation:
- Player 4 → Trainer 5 or 8 (match ✅)
- Player 7 → Trainer 8 (match ✅)
- Player 9 → No trainer with ≥ 9
Max matchings = 2
🧠Explanation:
To maximize matchings:
- Match weakest players with weakest possible trainers who can still train them.
- This is a classic greedy strategy.
So:
- Sort both arrays
- Use two pointers (
i
for players,j
for trainers) - Try to assign trainers in increasing order to the first available player they can handle.
- Time Complexity: O(n log n + m log m) and Space: O(1)
import java.util.Arrays;
public class Solution {
public int matchPlayersAndTrainers(int[] players, int[] trainers) {
Arrays.sort(players);
Arrays.sort(trainers);
int i = 0, j = 0;
int matchCount = 0;
while (i < players.length && j < trainers.length) {
if (players[i] <= trainers[j]) {
matchCount++;
i++;
j++;
} else {
j++; // trainer too weak, check next trainer
}
}
return matchCount;
}
}