There are n jobs. Job i has a difficulty difficulty[i] and pays profit[i]. There are also m workers, and worker j can only take a job whose difficulty is at most worker[j].
Each worker does at most one job, but the same job may be done by any number of workers, and each time it pays in full. A worker who can do no job earns nothing. Return the largest total pay you can get by choosing a job for each worker.
Example 1
Input: difficulty = [5, 2, 8, 4], profit = [15, 9, 12, 20], worker = [3, 6, 9, 1] Output: 49 Why: workers earn 9, 20, 20 and 0
2 more examples and the constraints
Example 2
Input: difficulty = [30, 50], profit = [7, 3], worker = [10, 20] Output: 0 Why: every job is too hard for every worker
Example 3
Input: difficulty = [3, 3, 3], profit = [4, 11, 6], worker = [3, 5] Output: 22 Why: both workers take the job that pays 11
Constraints
- 1 ≤ n, m ≤ 10,000
- difficulty and profit both have length n; worker has length m
- 1 ≤ every difficulty, profit and ability ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan every job per workerO(n·m)
- Sort both, sweep with a running bestO(n log n + m log m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = m = 10,000 | Verdict |
|---|---|---|---|
| Scan every job per worker | O(n·m) | Correct, but 10⁸ checks | |
| Sort both, sweep with a running best | O(n log n + m log m) | Best; one sweep after sorting |
n = number of jobs, m = number of workers.
Edge cases to test
- No worker can do anything. Every job is too hard: the answer is 0.
- Same difficulty, different pay. Several jobs at difficulty 3 paying 4, 11 and 6: take 11.
- Harder job pays less. d5 pays $15 but d4 pays $20; a worker of ability 6 still earns 20.
- Ability equals difficulty. The rule is at most, so a worker of ability 4 can do a job of difficulty 4.
- Many workers, one job. Every worker may take the same job, and each one is paid.
Common mistakes
- Giving each worker the hardest job they can do instead of the best-paying one.
- Sorting difficulty and profit separately, which breaks the pairing.
- Resetting the job pointer or
bestfor each worker, turning the sweep back into O(n·m).
How to talk through it
- 1Clarify. Can several workers do the same job? Is a job doable when its difficulty equals the ability?
- 2Give the brute force. For each worker, scan every job; O(n·m), 10⁸ at the limit.
- 3Notice the order. A stronger worker can do every job a weaker one can, so best pay only grows.
- 4Code the sweep. Sort both lists, move one job pointer forward, keep a running best.
- 5Test out loud. Run a case where a harder job pays less and one where nobody qualifies.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?