Problem Description
You are given an array of integers g representing the greed factors of children and an array of integers s representing the sizes of cookies. A child will be content if they receive a cookie with a size greater than or equal to their greed factor. The goal is to maximize the number of content children by distributing the cookies, where each child can receive at most one cookie.
Key Insights
- Sort both the greed factor array and the cookie sizes array.
- Use a two-pointer approach to iterate through both arrays.
- If the current cookie can satisfy the current child's greed, assign it and move to the next child.
- Continue until either all children are checked or all cookies are used.
Space and Time Complexity
Time Complexity: O(n log n + m log m) where n is the number of children and m is the number of cookies (due to sorting). Space Complexity: O(1) if sorting is done in-place, otherwise O(n + m) if extra space is used to copy lists.
Solution
The approach is based on greedy allocation. By sorting the children based on their greed factors and sorting the cookies by size, we can efficiently match the smallest available cookie that is sufficient for a given child. The two-pointer technique helps in traversing both arrays simultaneously, ensuring that we don’t waste a potentially larger cookie on a child with lower greed if a smaller cookie would suffice. This strategy maximizes the number of content children.