Graph Theory37 sections · 1633 units
Open in Course

Assign Cookies - Implementation

(Greedy two pointers)

Here is both the greedy and matching approach:

// Greedy approach (faster)
function assignCookiesGreedy(children, cookies):
    sort children ascending
    sort cookies ascending

    i = 0  // child pointer
    j = 0  // cookie pointer
    count = 0

    while i < children.length and j < cookies.length:
        if cookies[j] >= children[i]:
            count = count + 1
            i = i + 1
        j = j + 1

    return count

// Matching approach (for learning)
function assignCookiesMatching(children, cookies):
    adj = empty adjacency list
    for i from 0 to children.length - 1:
        for j from 0 to cookies.length - 1:
            if cookies[j] >= children[i]:
                adj[i].append(j)

    return kuhnMaxMatching(children.length, cookies.length, adj)

Time: O(nlogn)O(n \log n) for greedy, O(VE)O(VE) for matching. Space: O(V)O(V).