[Leetcode] 2410. Maximum Matching of Players With Trainers

whitehousechef·2025년 7월 13일

https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/?envType=daily-question&envId=2025-07-13

initial

i solved it but

while... 
	if sth:
    	break

this break breaks the while loop and the code below the while block still runs! I wanted to return answer after this if statement but instead of break, u should return ans

sol

class Solution:
    def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
        players.sort()
        ans=0
        trainers.sort()
        idx=0
        for player in players:
            if idx==len(trainers):
                break
            while trainers[idx]<player:
                idx+=1
                if idx==len(trainers):
                    return ans
            # if trainers[idx]>=player:
            ans+=1
            idx+=1
        return ans
            

revisited 16th oct 2025

u can solve with heap

import heapq

def matchPlayersAndTrainers(players, trainers):
    # Create min-heap from players
    heap = players[:]
    heapq.heapify(heap)
    
    # Sort trainers
    trainers.sort()
    
    matches = 0
    
    # Iterate through trainers
    for trainer in trainers:
        # Try to match with the smallest player who qualifies
        if heap and heap[0] <= trainer:
            heapq.heappop(heap)
            matches += 1
    
    return matches

complexity

n^2 time cuz double for loop?
no the pointers run for n+m time, while sorting is n log n
so it is n log n + m long m that is the dominant time

1 space

0개의 댓글