Coat Drive Handout

EasygreedyAlso known as Assign Cookies

A winter coat drive has a pile of donated coats, each tagged with a warmth rating. Each person in line tells you the lowest rating that will keep them warm, and is happy with any coat rated at least that.

Each coat goes to one person, and each person takes at most one coat. Get as many people as possible walking away warm.

Your task

Write maxWarmPeople(needs, coats). needs[i] is the lowest warmth person i accepts. coats[j] is the warmth of coat j. Return the largest number of people who can each get a coat with coats[j] ≥ needs[i].

Either list may be empty; then the answer is 0. Neither list is sorted.

maxWarmPeople(needs: int[], coats: int[]) → int

Examples

Example 1
Input
needs = [3, 6, 4]
coats = [2, 5, 4]
Output
2
Why

The coat rated 2 is too thin for everyone. The 4 can go to the person needing 3, and the 5 can go to the person needing 4. No coat is warm enough for the person needing 6, so 2 people get coats.

Example 2
Input
needs = [2, 7]
coats = [8, 2]
Output
2
Why

If you hand out the first coat that fits, the person needing 2 takes the 8 and the person needing 7 gets nothing. If you give the 2 to the first person and the 8 to the second, both are warm.

Constraints

  • 0 ≤ needs.length ≤ 10,000
  • 0 ≤ coats.length ≤ 10,000
  • 1 ≤ needs[i], coats[j] ≤ 1,000
Start with brute force

Try every way of handing out coats: for each person, each unused coat that fits, or none, and keep the best total. The number of matchings explodes: even 20 people and 20 coats is far beyond any computer.

A gentler first idea gives each person in line the first coat in the pile that fits. It is fast but wrong: in the second example a needy person loses out because a warm coat went to someone who needed very little.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code