VOOZH about

URL: https://www.geeksforgeeks.org/dsa/assign-cookies/

⇱ Assign Maximum Cookies - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Assign Maximum Cookies

Last Updated : 2 Sep, 2025

Given two arrays, greed[] and cookie[] such that greed[i] denotes the minimum cookie size wanted by ith child and cookie[i] denotes the size of ith cookie, we have to find the maximum number of children that can be satisfied by assigning them cookies, with each child getting at most 1 cookie.

Note: A child will be satisfied if he is assigned a cookie of size at least equal to his greed. In other words, the ith child will be satified with jth cookie only if greed[i] <= cookie[j].

Examples:

Input: greed[] = [1, 10, 3], cookie[] = [1, 2,3]
Output: 2
Explanation: We can only assign cookie to the first child and third child.

Input: greed[] = [10,100], cookie[] = [1, 2]
Output: 0
Explanation: We can not assign cookies to children.

[Approach] Using Sorting and Two Pointer - O(nlogn + mlogm) Time and O(1) Space

The idea is to assign smallest cookie to each child greedily such that the child gets satisfied. So, we can sort both greed[] and cookie[] and start assigning the smallest cookies to the children with smallest greed.

Steps to solve the problem:

  • Sort the greed array greed and the cookie arrays.
  • Initialize two pointers: i (index for children), j (index for cookies)
  • Initialize count = 0 to track the number of satisfied children.
  • Iterate while both pointers are within their array bounds:
  • If cookie[j] >= greed[i], the cookie can satisfy the child: Increment count and Move both pointers .
  • Else cookie is too small and Move only the cookie pointer/
  • Return count as the total number of satisfied children.

Output
2
Comment
Article Tags:
Article Tags: