代码随想录--贪心--分饼干

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

对每个孩子 i,都有一个胃口值 gi,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 sj 。如果 sj >= gi,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

示例 1:

  • 输入: g = 1,2, s = 1,2,3
  • 输出: 2
  • 解释:你有两个孩子和三块小饼干,2 个孩子的胃口值分别是 1,2。你拥有的饼干数量和尺寸都足以让所有孩子满足。所以你应该输出 2.
java 复制代码
import java.util.Arrays;

public class Cookie {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int count = 0;
        int start = s.length - 1;
        // 遍历胃口
        for (int index = g.length - 1; index >= 0; index--) {
            if(start >= 0 && g[index] <= s[start]) {
                start--;
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        //g = [1,2,3], s = [1,1]
        int[] g = {1,2};
        int[] s = {1,2,3};

        Cookie cookie = new Cookie();
        int res = cookie.findContentChildren(g, s);
        System.out.println(res);
    }
}
相关推荐
大熊背19 分钟前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2581 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲1 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力551 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜2 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者2 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
_Narcissus_2 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.2 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks2 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路3 小时前
算法8.环形队列
算法