#2410
Maximum Matching of Players With Trainers
MediumArrayTwo PointersGreedySortingTwo PointersGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting both arrays and using a two-pointer technique, we can efficiently find matches without unnecessary comparisons. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Sort both the players and trainers arrays.
- 2Step 2: Initialize two pointers, one for players and one for trainers.
- 3Step 3: Iterate through both arrays, moving the player pointer forward when a match is found, and always moving the trainer pointer forward.
solution.py14 lines
1def maxMatches(players, trainers):
2 players.sort()
3 trainers.sort()
4 matches = 0
5 i, j = 0, 0
6 while i < len(players) and j < len(trainers):
7 if players[i] <= trainers[j]:
8 matches += 1
9 i += 1
10 j += 1
11 return matches
12
13# Example usage
14print(maxMatches([4, 7, 9], [8, 2, 5, 8]))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the matching process is O(n), making it much more efficient than the brute force approach.
- 1Sorting helps in efficiently finding matches.
- 2Using two pointers reduces unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.