I am learning greedy algorithm and it's applications. The question below is the first one of the many provided in the book to learn greedy algorithm.
Q) There is n number of children and you have m > n number of chocolate to distribute. You must give each child exactly one chocolate (of course, you cannot give the same chocolate to two different children). Each child has an appetite factor ai, 1 ≤ i ≤ n which is the minimum size of a chocolate that the child will be happy with; and each chocolate has a size sj , 1 ≤ j ≤ m. Your goal is to maximize the number of happy children, i.e., children i assigned a chocolate j with gi ≤ sj..
I would really appreciate it if anyone could help me the solution to this question. There are a few more like this but I think I will be able to do them if i can do this one.
Thanks!
You've correctly identified the algorithm in the comments:
we have to assign the cookies in ascending order and whenever possible assign it the least greediest child
You can break the algorithm down into simple steps, like this
Sort the cookies ascending by size
For each cookie in the sorted list
if the least greedy child remaining will be happy with that cookie
give the cookie to the least greedy child