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

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

对每个孩子 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);
    }
}
相关推荐
ocean210334 分钟前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2081 小时前
leetcode 78子集
数据结构·算法·leetcode
喜欢吃燃面1 小时前
深入 C++ STL:从 unordered_set与unordered_map到底层哈希表的原理与实现
数据结构·c++·散列表
en.en..2 小时前
Linux fork() 工作原理
数据结构·算法
地平线开发者2 小时前
bevformer算法模型详细解读
算法
liliangcsdn3 小时前
ICIR权重矩阵如何加权标准化为综合因子
算法
SDWAN_Cheap3 小时前
SD-WAN智能选路技术的算法与实现机制
算法·php·sdwan
不会就选b4 小时前
数据结构之树&&二叉树(二)
数据结构·算法
渡之4 小时前
ArduPilot (APM)滤波器之SlewLimiter 深度解析
算法
zander2584 小时前
LeetCode 1143. 最长公共子序列
开发语言·python·算法