Leetcode Assign Cookies problem solution YASH PAL, 31 July 2024 In this Leetcode Assign Cookies problem solution 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. Problem solution in Python. class Solution(object): def findContentChildren(self, g, s): count = 0 g.sort() # kids s.sort() # cookies cookie_i, kid_i = 0, 0 while cookie_i < len(s) and kid_i < len(g): if s[cookie_i] >= g[kid_i]: kid_i += 1 count += 1 cookie_i += 1 return count Problem solution in Java. public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int i = 0, j = 0; while (i < g.length && j < s.length) { if (g[i] <= s[j]) { i++; } j++; } return i; } Problem solution in C++. class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); sort(s.begin(), s.end()); int n = g.size(); int m = s.size(); int i = 0; int j = 0; int ans = 0; while(i < n && j < m) { if(s[j] >= g[i]) { ans++; i++; j++; } else { j++; } } return ans; } }; Problem solution in C. int comp (const void *a, const void *b) { return *((int *)a) - *((int *)b); } int findContentChildren(int* g, int gSize, int* s, int sSize) { qsort(g, gSize, sizeof(int), comp); qsort(s, sSize, sizeof(int), comp); int count = 0; int j = 0; for (int i = 0; i < sSize; i ++) { if (s[i] >= g[j]) { count += 1; j += 1; if (j >= gSize) break; } } return count; } coding problems