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 <vector>
2#include <algorithm>
3#include <iostream>
4
5class Solution {
6public:
7 int findContentChildren(std::vector<int>& g, std::vector<int>& s) {
8 std::sort(g.begin(), g.end());
9 std::sort(s.begin(), s.end());
10
11 int i = 0, j = 0;
12 while (i < g.size() && j < s.size()) {
13 if (s[j] >= g[i]) {
14 i++;
15 }
16 j++;
17 }
18 return i;
19 }
20};
21
22int main() {
23 Solution solution;
24 std::vector<int> g = {1, 2, 3};
25 std::vector<int> s = {1, 1};
26 int result = solution.findContentChildren(g, s);
27 std::cout << result << std::endl;
28 return 0;
29}
This C++ solution sorts the greed factor and cookie arrays and uses two pointers to count the maximum number of children that can be satisfied. The algorithm increments the children's pointer when a cookie satisfies a child.
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.