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
Returns (int) 1

Example 2

Input
greed (int[]) = [1,2]
gSize (int) = 2
cookies (int[]) = [1,2,3]
cSize (int) = 3
Returns (int) 2

Example 3

Input
greed (int[]) = [10]
gSize (int) = 1
cookies (int[]) = [1,2]
cSize (int) = 2
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.