Maximum Matching of Players With Trainers - Problem

You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer.

The ith player can match with the jth trainer if the player's ability is less than or equal to the trainer's training capacity. Additionally, the ith player can be matched with at most one trainer, and the jth trainer can be matched with at most one player.

Return the maximum number of matchings between players and trainers that satisfy these conditions.

Input & Output

Example 1 — Basic Case
$ Input: players = [4,7,9], trainers = [8,2,5,8]
Output: 2
💡 Note: We can match player 4 with trainer 5 (4 ≤ 5) and player 7 with trainer 8 (7 ≤ 8). Player 9 cannot be matched since no remaining trainer has capacity ≥ 9.
Example 2 — All Players Match
$ Input: players = [1,1,1], trainers = [10]
Output: 1
💡 Note: Only one trainer available, so we can match at most one player. All players have ability 1 ≤ 10, but each trainer can only match with one player.
Example 3 — No Matches Possible
$ Input: players = [10,20,30], trainers = [5,6,7]
Output: 0
💡 Note: No player can be matched because every player's ability exceeds every trainer's capacity.

Constraints

  • 1 ≤ players.length, trainers.length ≤ 105
  • 1 ≤ players[i], trainers[j] ≤ 109

Visualization

Tap to expand
Maximum Matching: Players With TrainersPlayers (Ability):479Trainers (Capacity):8258Matching Rule: Player Ability ≤ Trainer Capacity✓ Player 4 matches Trainer 5 (4 ≤ 5)✓ Player 7 matches Trainer 8 (7 ≤ 8)✗ Player 9 cannot match (no available trainer ≥ 9)Maximum Matches: 2
Understanding the Visualization
1
Input
Players with abilities and trainers with capacities
2
Matching Rule
Player ability ≤ trainer capacity, 1-to-1 matching
3
Output
Maximum number of valid matches possible
Key Takeaway
🎯 Key Insight: Sort both arrays and greedily match each player with the weakest suitable trainer
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
32.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen