Leet Code 455. 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.


这道题是一道最简单的贪心算法的题目了...

也就是让我们从一堆的饼干里面尽可能的满足多的人...

假设有5个人..他们的需求分别是

10,5,8,9,1

我们有4个饼干.大小分别为

8,2,4,15

那么首先我们对两个数组都进行排序,,这里使用倒叙

那么分别是

10,9,8,5,1

15,8,4,2

所以我们可以遍历第一个数组,如果第二个数组的第一位(当前最大饼干值)能满足他,那么就说明能满足一个人,如果不行的话就说明这个人的需求已经满足不了了.因为每个人能且仅能给一个饼干而已...

所以代码如下:

public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
        if(s.Length == 0 || g.Length == 0)
            return 0;
        Array.Sort(s);
        Array.Sort(g);
        int success = 0;
        int index = s.Length-1;
        for(int i=g.Length-1;i>=0;i--)
        {
            if(index<0)
                break;
            if(g[i]<=s[index])
            {
                success++;
                index--;
            }
        }
        return success;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值