2410: Maximum-Matching-of-Players-With-Trainers
Medium


table of contents

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 taken