算法分析與設計第七週作業
題目
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.
題目傳送門
解讀
有一堆餅乾和一堆孩子,每個餅乾大小爲s[j],每個孩子想要的大小爲g[i],求這堆餅乾能滿足至多多少個孩子?
這是一個貪心算法能夠解決的問題,很容易想到,每個孩子儘量拿到和他想要的大小差距最小的餅乾,就能保證不會“浪費”大塊餅乾。因此把g和s排序後,把最相鄰的餅乾分給剛剛好滿足的孩子,就能得到最大的滿足數量了。
解答
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int i=0, j=0;
int count = 0;
for(; j<s.size() && i<g.size(); j++) {
if(g[i] <= s[j]) {
count ++;
i++;
}
}
return count;
}
};