Learner Level

Implement the assignCookiesMaximumChildren method that returns the maximum number of children that can receive a suitable cookie.

The input contains two arrays. greed stores the minimum cookie size each child needs to be satisfied, and cookies stores the available cookie sizes.

Each child can receive at most one cookie, and each cookie can be used only once. Your task is to return the maximum number of children that can be satisfied.

For example, if greed is [1,2,3] and cookies are [1,1], only one child can be satisfied, so the answer is 1.

Example 1
Input:
greed (int[]) = [1,2,3]
gSize (int) = 3
cookies (int[]) = [1,1]
cSize (int) = 2
Return:
(int) 1
Example 2
Input:
greed (int[]) = [1,2]
gSize (int) = 2
cookies (int[]) = [1,2,3]
cSize (int) = 3
Return:
(int) 2
Example 3
Input:
greed (int[]) = [10]
gSize (int) = 1
cookies (int[]) = [1,2]
cSize (int) = 2
Return:
(int) 0

Sort both arrays and use the smallest suitable cookie for each child.

Start with the least greedy child and the smallest cookie. If the cookie can satisfy the child, count that child and move to the next child and next cookie. If the cookie is too small, discard that cookie and try the next larger one.

This greedy method saves larger cookies for children who need them more.

Pseudocode:

function assignCookiesMaximumChildren(greed, gSize, cookies, cSize):
    sort greed ascending
    sort cookies ascending
    child = 0
    cookie = 0
    satisfied = 0
    while child < gSize and cookie < cSize:
        if cookies[cookie] >= greed[child]:
            satisfied++
            child++
            cookie++
        else:
            cookie++
    return satisfied
Run your code to see the result.