|
| 1 | +# 455. Assign Cookies |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: Array, Two Pointers, Greedy, Sorting. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. |
| 10 | + |
| 11 | +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. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: g = [1,2,3], s = [1,1] |
| 18 | +Output: 1 |
| 19 | +Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. |
| 20 | +And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. |
| 21 | +You need to output 1. |
| 22 | +``` |
| 23 | + |
| 24 | +Example 2: |
| 25 | + |
| 26 | +``` |
| 27 | +Input: g = [1,2], s = [1,2,3] |
| 28 | +Output: 2 |
| 29 | +Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. |
| 30 | +You have 3 cookies and their sizes are big enough to gratify all of the children, |
| 31 | +You need to output 2. |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +**Constraints:** |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +- `1 <= g.length <= 3 * 104` |
| 40 | + |
| 41 | +- `0 <= s.length <= 3 * 104` |
| 42 | + |
| 43 | +- `1 <= g[i], s[j] <= 231 - 1` |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +## Solution |
| 48 | + |
| 49 | +```javascript |
| 50 | +/** |
| 51 | + * @param {number[]} g |
| 52 | + * @param {number[]} s |
| 53 | + * @return {number} |
| 54 | + */ |
| 55 | +var findContentChildren = function(g, s) { |
| 56 | + g.sort((a, b) => a - b); |
| 57 | + s.sort((a, b) => a - b); |
| 58 | + var j = 0; |
| 59 | + for (var i = 0; i < g.length; i++) { |
| 60 | + while (s[j] < g[i] && j < s.length) j++; |
| 61 | + if (j === s.length) return i; |
| 62 | + j++; |
| 63 | + } |
| 64 | + return g.length; |
| 65 | +}; |
| 66 | +``` |
| 67 | + |
| 68 | +**Explain:** |
| 69 | + |
| 70 | +nope. |
| 71 | + |
| 72 | +**Complexity:** |
| 73 | + |
| 74 | +* Time complexity : O(n * log(n)). |
| 75 | +* Space complexity : O(1). |
0 commit comments