Skills101
← All coding problems

Assign Cookies

easyGreedy+10 XPTime limit 2s

Child i is happy with a cookie of size at least greed[i]. You have cookies of sizes size[j]; each child gets at most one cookie and each cookie goes to at most one child. Maximise the number of happy children.

Input:

  • line 1: n m — children and cookies
  • line 2: the n greed values
  • line 3: the m cookie sizes (empty if m = 0)

Output: the maximum number of happy children.

Constraints: 1 ≤ n ≤ 3·10⁴, 0 ≤ m ≤ 3·10⁴, 1 ≤ values ≤ 2³¹ − 1.

Think about it: sort both lists. Walk through the cookies from small to large and give each one to the least greedy child still waiting, if it satisfies them. Why is it never better to "save" a cookie?

Sample input 1

3 2
1 2 3
1 1

Sample output 1

1

Sample input 2

2 3
1 2
1 2 3

Sample output 2

2

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.