DevPath

← All problems

Assign Cookies

Easy greedy · sorting

Description

Each child has a greed factor and each cookie has a size. Return the maximum number of children you can satisfy (cookie size >= greed).

Constraints

1 <= n, m <= 100000

Examples

Input: greed = [1,2,3], size = [1,1]

Output: 1

Hints (1)
  • Sort both and give the smallest sufficient cookie.

Solutions

Two-pointer greedy. (requires "sort") · Time O(n log n) · Space O(1)

func findContentChildren(greed, size []int) int {
    sort.Ints(greed)
    sort.Ints(size)
    i, j, count := 0, 0, 0
    for i < len(greed) && j < len(size) {
        if size[j] >= greed[i] {
            count++
            i++
        }
        j++
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account