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 of Players With Trainers INPUT Players (abilities) 4 7 9 players = [4, 7, 9] Trainers (capacity) 8 2 5 8 trainers = [8, 2, 5, 8] Condition: player ability <= trainer capacity P Player T Trainer ALGORITHM (Greedy) 1 Sort both arrays P:[4,7,9] T:[2,5,8,8] 2 Two pointers: i=0, j=0 Match count = 0 3 Compare and match If P[i]<=T[j]: match++ 4 Move pointers Always advance j++ Iterations: j=0: T[0]=2 < P[0]=4 (skip) j=1: T[1]=5 >= P[0]=4 (MATCH!) j=2: T[2]=8 >= P[1]=7 (MATCH!) j=3: T[3]=8 < P[2]=9 (skip) j=4: out of bounds, STOP Total matches: 2 FINAL RESULT Valid Matchings 4 5 4 <= 5 OK 7 8 7 <= 8 OK Unmatched: 9 2 8 Output: 2 Maximum matchings found! Key Insight: By sorting both arrays, we can use a greedy two-pointer approach. Match the smallest available player with the smallest trainer that can handle them. This ensures we don't waste higher-capacity trainers on players who could be matched with lower-capacity ones. Time: O(n log n), Space: O(1) TutorialsPoint - Maximum Matching of Players With Trainers | Greedy Approach
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