Leetcode 455: Assign Cookies

grid47
grid47
Exploring patterns and algorithms
Sep 22, 2024 5 min read

A series of cookies and children with glowing indicators of the best cookie assignment.
Solution to LeetCode 455: Assign Cookies Problem

You are a parent with several children and a set of cookies. Each child has a greed factor, which is the minimum size of a cookie they will be happy with. Each cookie also has a size. Your task is to distribute the cookies such that you maximize the number of content children. Each child can receive at most one cookie, and each cookie can only be given to one child.
Problem
Approach
Steps
Complexity
Input: The input consists of two arrays: one representing the greed factors of children and another representing the sizes of cookies.
Example: g = [1, 2, 3], s = [1, 1]
Constraints:
• 1 <= g.length <= 3 * 10^4
• 0 <= s.length <= 3 * 10^4
• 1 <= g[i], s[j] <= 231 - 1
Output: Return the maximum number of content children that can be satisfied by the cookies.
Example: Output: 1
Constraints:
• The result should be the number of content children that can be satisfied.
Goal: The goal is to find the maximum number of children that can be satisfied by distributing the cookies.
Steps:
• 1. Sort both the greed factors and the sizes of cookies in ascending order.
• 2. Use a two-pointer approach: one pointer for the children and one for the cookies.
• 3. Iterate through the sorted arrays and try to match the smallest available cookie that can satisfy each child. If a match is found, move to the next child and the next cookie.
Goal: The solution must handle large inputs efficiently.
Steps:
• The algorithm must handle arrays of size up to 30,000 efficiently.
Assumptions:
• Each child and cookie has a non-negative greed factor and size respectively.
• Cookies may not be large enough to satisfy all children.
Input: g = [1, 2, 3], s = [1, 1]
Explanation: In this case, you can only satisfy one child, as both cookies are too small to satisfy the children with greed factors of 2 and 3.

Input: g = [1, 2], s = [1, 2, 3]
Explanation: Here, both children can be satisfied because there are enough cookies of suitable size.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus