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.
1function findContentChildren(g, s) {
2 g.sort((a, b) => a - b);
3 s.sort((a, b) => a - b);
4 let i = 0, j = 0;
5 while (i < g.length && j < s.length) {
6 if (s[j] >= g[i]) {
7 i++;
8 }
9 j++;
10 }
11 return i;
12}
13
14console.log(findContentChildren([1, 2, 3], [1, 1]));
This JavaScript solution involves sorting the greed and size arrays, after which it uses a straightforward two-pointer method to match cookies to children and determines how many children get their desired cookies.
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.