[LeetCode] 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 g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(begin(g), end(g));
sort(begin(s), end(s));
int res = 0;
for(int i = 0, j = 0; i < g.size() and j < s.size(); i++) {
while(j < s.size() and g[i] > s[j]) j++;
if(j == s.size()) break;
j += 1, res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/01/PS/LeetCode/assign-cookies/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.