LeetCode455-Assign Cookies

题目

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.

Note:

You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

Example1:

Input: [1,2,3], [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.

Example2:

Input: [1,2], [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.

分析

试想一种最好最妙的情况:就是以最少数量、最恰好尺寸的饼干满足了所有小朋友的胃口。比如

Input: [1,2,3,4,5], [1,2,3,4,5]
Output: 5

可以看出,分配策略自然是胃口小的小朋友分到小饼干胃口大的分到大饼干。设想一下,如果我们把尺寸为3的饼干拿走了,那么此时对\({g_4}\)和\({g_5}\)的分法就有两种方案:

  • 方案一:\({g_4}\)分给\({s_4}\),\({g_5}\)分给\({s_5}\)
  • 方案二:\({g_4}\)分给\({s_3}\),\({g_5}\)分给\({s_4}\)

显然,因为我们只管最后分到的小朋友人头数最多,所以方案二显然更保险些。因为万一\({s_4}\)和\({s_5}\)原来的胃口是6和7呢,那此时方案二的优势就出来了,因为它优先满足了胃口小\({s_3}\)多获得了一个人头数。

所以总结下就是一句话:用最小尺寸的饼干优先满足胃口小的小朋友!既然涉及顺序,那么必然先对两个数组进行排序,然后再优先移动cookie游标寻找能满足child的饼干,若满足两者同时下移,若不满足仅下移cookie(为什么不下移child?因为胃口数组是按升序排好序了的,当前的child都无法满足更不要说之后的child了)。

代码

public class Solution {
    public int findContentChildren(int[] g, int[] s) {

        Arrays.sort(g);
        Arrays.sort(s);
        
        int count = 0;
        int child = 0, cookie = 0;
        while(child < g.length && cookie < s.length) {
            if(s[cookie] >= g[child]) {
                count++;
                cookie++;
                child++;
            } else {
                cookie++;   
            }
        }
        
        return count;
    }
}

Leave a Comment.