-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
71 lines (66 loc) · 2.32 KB
/
main.go
File metadata and controls
71 lines (66 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Source: https://leetcode.com/problems/maximum-matching-of-players-with-trainers
// Title: Maximum Matching of Players With Trainers
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You are given a **0-indexed** integer array `players`, where `players[i]` represents the **ability** of the `i^th` player. You are also given a **0-indexed** integer array `trainers`, where `trainers[j]` represents the **training capacity **of the `j^th` trainer.
//
// The `i^th` player can **match** with the `j^th` trainer if the player's ability is **less than or equal to** the trainer's training capacity. Additionally, the `i^th` player can be matched with at most one trainer, and the `j^th` trainer can be matched with at most one player.
//
// Return the **maximum** number of matchings between `players` and `trainers` that satisfy these conditions.
//
// **Example 1:**
//
// ```
// Input: players = [4,7,9], trainers = [8,2,5,8]
// Output: 2
// Explanation:
// One of the ways we can form two matchings is as follows:
// - players[0] can be matched with trainers[0] since 4 <= 8.
// - players[1] can be matched with trainers[3] since 7 <= 8.
// It can be proven that 2 is the maximum number of matchings that can be formed.
// ```
//
// **Example 2:**
//
// ```
// Input: players = [1,1,1], trainers = [10]
// Output: 1
// Explanation:
// The trainer can be matched with any of the 3 players.
// Each player can only be matched with one trainer, so the maximum answer is 1.
// ```
//
// **Constraints:**
//
// - `1 <= players.length, trainers.length <= 10^5`
// - `1 <= players[i], trainers[j] <= 10^9`
//
// **Note:** This question is the same as https://leetcode.com/problems/assign-cookies/
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
import (
"slices"
)
// Greedy
//
// Sort the players and trainers, and match from the minimal.
func matchPlayersAndTrainers(players []int, trainers []int) int {
n := len(players)
m := len(trainers)
slices.Sort(players)
slices.Sort(trainers)
ans := 0
i, j := 0, 0
for i < n && j < m {
if players[i] <= trainers[j] {
i++
j++
ans++
} else {
j++
}
}
return ans
}