贪心0

shimmer / 2023-08-12 / 原文

题目分类大纲

一、简单题目

1.分发饼干

题目描述

题目链接
参考题解

解题思路

  • 为了满足更多的小孩,就不要造成饼干尺寸的浪费。

  • 大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的。

  • 这里的局部最优就是大饼干喂给胃口大的,充分利用饼干尺寸喂饱一个,全局最优就是喂饱尽可能多的小孩。

代码

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int result = 0;
        int index = s.length-1;   //饼干尺寸
        for(int i=g.length-1; i>=0; i--) {
            if(index>=0 && s[index] >= g[i]) {
                result++;
                index--;
            }
        }
        return result;
    }
}