[LeetCode] 455. Assign Cookies 分配饼干

题目

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.

思路

如果能优先用最小的饼干满足最小贪欲的孩子,那么最终就能满足更多的孩子。此即贪心算法的运用。

代码

func findContentChildren(g []int, s []int) int {
    sort.Ints(g)
    sort.Ints(s)
    var gi, si int
    for gi < len(g) && si < len(s) {
        if g[gi] <= s[si] {
            gi++
        }
        si++
    }
    return gi
}

发表于:2019年03月12日 ,阅读量:28 ,标签:算法 · LeetCode · 贪心算法

版权声明:若非特别注明,本站所有文章均为作者原创,转载请务必注明原文地址。