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.
1using System;
2
3class Program {
4 public static int FindContentChildren(int[] g, int[] s) {
5 Array.Sort(g);
6 Array.Sort(s);
7
8 int i = 0, j = 0;
9 while (i < g.Length && j < s.Length) {
10 if (s[j] >= g[i]) {
11 i++;
12 }
13 j++;
14 }
15 return i;
16 }
17
18 static void Main() {
19 int[] g = {1, 2, 3};
20 int[] s = {1, 1};
21 Console.WriteLine(FindContentChildren(g, s));
22 }
23}
In C#, the solution uses built-in sorting for both arrays and employs a pair of pointers to track and find the number of children a cookie can satisfy using condition checks.
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.
This Java solution looks through sorted greed then iteratively relies on a loop to ensure each selected child finds a proper cookie, advancing as repeatedly needed per lack of matching.