455. Assign Cookies
Easy
Problem:
Each child must be given one cookie. Each child, denoted as child_i, has a greed factor, which represents the minimum size of the cookie the child will be satisfied with. Each cookie, cookie_j, has a size, and a child will be satisfied and accept the cookie if s[cookie_j] >= g[child_i]. Print the maximum number of children who can be given a cookie.
Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
https://leetcode.com/problems/assign-cookies/description/
What to learn:
bisect_left()
returns the index of the found value's position, while bisect_right()
returns the index after the found value's position.
>>> bisect.bisect_left([1,2,3,4,5], 3)
2
>>> bisect.bisect_right([1,2,3,4,5], 3)
3
Solution:
Greedy algorithm
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
g_p, s_p = 0, 0
while g_p < len(g) and s_p < len(s):
if s[s_p] >= g[g_p]:
g_p += 1
s_p += 1
return g_p
Binary search
While iterating through one list, search for the corresponding index in the other list using binary search. If the found index is greater than the current number of children assigned cookies, it means that more cookies can be given, so increase the count of children who can be given cookies by one.
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
result = 0
for i in s:
index = bisect.bisect_right(g, i)
if index > result:
result += 1
return result
Last updated