Sponsored
Sponsored
This approach involves sorting the greed factors and cookie sizes. By sorting, the goal is to try to satisfy the least greedy child first with the smallest satisfying cookie. By continuing this way, the solution can maximize the number of content children.
The solution uses two pointers, one for the greed list (g
) and one for the cookie size list (s
). It increments the pointer for the children only when a matching cookie is found.
Time Complexity: O(n log n + m log m), where n is the number of children and m is the number of cookies (due to sorting).
Space Complexity: O(1), as it uses a constant amount of extra space apart from the input arrays.
1#include <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 return (*(int*)a - *(int*)b);
6}
7
8int findContentChildren(int* g, int gSize, int* s, int sSize) {
9 qsort(g, gSize, sizeof(int), compare);
10 qsort(s, sSize, sizeof(int), compare);
11
12 int i = 0, j = 0;
13 while (i < gSize && j < sSize) {
14 if (s[j] >= g[i]) {
15 i++;
16 }
17 j++;
18 }
19 return i;
20}
21
22int main() {
23 int g[] = {1, 2, 3};
24 int s[] = {1, 1};
25 int result = findContentChildren(g, 3, s, 2);
26 printf("%d\n", result);
27 return 0;
28}
This C solution sorts both arrays and uses a two-pointer technique. It keeps a pointer on both the greed factors array and the cookie sizes array. By incrementing both pointers when a child is satisfied, it ensures that all possible cookies are used optimally.
This involves using binary search to attempt to find the proper index in the sorted list `s` where a given greed factor `g[i]` meets the condition.
For each child in the sorted greed list, perform binary search over the sorted cookie sizes to find the smallest suitable cookie. We'll mark the cookie as used by logically removing it from the pool (using an increment of the index pointer).
Time Complexity: O(n log n + n log m), where n is the number of the greed array, m is the number of cookie size array, originating from sorting and binary searching through the cookies.
Space Complexity: O(1) when not considering input arrays.
class Program {
public static int FindContentChildren(int[] g, int[] s) {
Array.Sort(g);
Array.Sort(s);
int contentChildrenCount = 0;
int cookieIndex = 0;
foreach (int greed in g) {
while (cookieIndex < s.Length && s[cookieIndex] < greed) {
cookieIndex++;
}
if (cookieIndex < s.Length) {
contentChildrenCount++;
cookieIndex++;
}
}
return contentChildrenCount;
}
static void Main() {
int[] g = {1, 2, 3};
int[] s = {1, 1};
Console.WriteLine(FindContentChildren(g, s)); // Output: 1
}
}
C# implements the practice leveraging sorting intrinsic methods and layering the search over child greeds through listings of cookies within enabled size fitments.