455.分发糖果(javascript)455.AssignCookies
原创假设你是一位伟大的家长,想给你的孩子一些饼干。然而,每个孩子最多只能给一块饼干。
对于每个孩子 i,都有食欲值 g[i]这是能满足儿童食欲的最小饼干尺寸。每一块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i]我们可以放这饼干 j 分配给孩子 i 孩子会满意的。你的目标是满足尽可能多的孩子,并输出这个最大值。
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 g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], 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.
示例 1:
输入: g = [1,2,3], s = [1,1]
输出: 1
解释:
你有三个孩子和两个饼干,3儿童的食欲值为:1,2,3。
虽然你有两个饼干,因为它们的大小是1,您只能使食欲值为。1孩子很满意。
所以你应该输出1。
示例 2:
输入: g = [1,2], s = [1,2,3]
输出: 2
解释:
你有两个孩子和三个饼干,2每个孩子的食欲值为1,2。
你的饼干数量和大小足够所有孩子吃。
所以你应该输出2.
Example 1:
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.
Example 2:
Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
为了满足更多的孩子,不要浪费饼干的大小。
大尺寸的饼干可以满足胃口大的孩子和胃口小的孩子,所以应该优先考虑胃口大孩子。
当地的最佳做法是给那些胃口大的人吃大饼干。充分利用饼干的大小来喂一个人。全球最佳做法是养活尽可能多的儿童。
//优先考虑食欲,先喂饱肚子。
var findContentChildren = function (g, s) {
g = g.sort((a, b) => b - a)
s = s.sort((a, b) => b - a)
let index = 0
for (let i = 0; i <= g.length; i++) {
if (index <= g.length && s[index] >= g[i]) {
index++
}
}
return index
};
leetcode: https://leetcode-cn.com/problems/assign-cookies/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123




