Coat Drive Handout

EasygreedyAlso known as Assign Cookies

A winter coat drive has a pile of donated coats. Each coat has a warmth rating printed on its tag. A line of people is waiting, and each person tells you the lowest warmth rating that would keep them warm enough.

A person is happy with any coat rated at least their number. Each coat can go to one person, and each person takes at most one coat. You want as many people as possible to walk 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 fits the person who needs 3 (or the one who needs 4), and the 5 fits the other one. The person who needs 6 cannot be helped by any coat. So 2 people get coats.

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

If you hand the first coat that fits to the first person, the person needing 2 takes the 8 and the person needing 7 gets nothing. Give the 2 to the person needing 2 and the 8 to the person needing 7, and 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, try each unused coat that fits, or no coat, and keep the best total. That is a search over all matchings, and the number of matchings explodes: with even 20 people and 20 coats it is far beyond what any computer can try.

A gentler-looking first idea is to go down the line and give each person the first coat in the pile that fits. It is fast, but it is wrong: the second example shows a needy person losing 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