[leetcode greedy]455. Assign Cookies

时间:2024-10-26 12:05:26

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

题意:把m块饼干分给n个孩子,每块饼干的尺寸为mi,每个孩子的要求尺寸为ni,最多可以使几个孩子满足?

思路:

排序,目标只分饼干,从小到大遍历饼干,只要有某个饼干可以满足某个孩子,就立马把饼干分出去,如果某块饼干不能满足最小的需求尺寸,立马舍弃这块饼干

 class Solution(object):
def findContentChildren(self, g, s):
g.sort()
s.sort()
n,i = 0,0
for si in s:
if i == len(g):
break
if si >= g[i]:
n += 1
i += 1
return n