Skip to content

← leetcode

Maximum Matching of Players With Trainers

· Medium

LeetCode problem 2410

First, sort both players and trainers in ascending order and then run a two pointers algorithm that iterate through both players and trainers, incrementing the number of matchings if there exists a trainer to train the current player.

code

class Solution {
public:
    int matchPlayersAndTrainers(vector<int>& players, vector<int>& trainers) {
        sort(players.begin(), players.end());
        sort(trainers.begin(), trainers.end());

        int playerIndex = 0;
        int trainerIndex = 0;
        int ans = 0;
        while (playerIndex < players.size() && trainerIndex < trainers.size()) {
            while(trainerIndex < trainers.size() && trainers[trainerIndex] < players[playerIndex]) {
                ++trainerIndex;
            }
            if (trainerIndex < trainers.size() && players[playerIndex] <= trainers[trainerIndex]) {
                ++ans;
                ++playerIndex;
                ++trainerIndex;
            }
        }
        return ans;
    }
};

complexity

  • Time: O(n log(n) + m log(m)) where n is the number of elements inside players, and m is the number of elements inside trainers
  • Space: O(1)

time taken

  • 5 minutes and 34 seconds