Maximum Matching of Players With Trainers Program In Java

Maximum Matching of Players With Trainers Program

🔷 Problem Statement:

You are given two integer arrays:

  • players → each value represents the ability of a player
  • trainers → each value represents the training capacity of a trainer

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:

  1. Sort both arrays
  2. Use two pointers (i for players, j for trainers)
  3. Try to assign trainers in increasing order to the first available player they can handle.
  4. 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;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top