[Leetcode Daily Notes] 455. Distribute Cookies (Python)

topic

Suppose you are a great parent and want to give your children some biscuits. However, each child can only give one cookie at most.

For each child i, there is an appetite value g[i], which is the smallest size of biscuit that can satisfy the appetite of the children; and each biscuit j has a size s[j]. If s[j] >= g[i], we can assign this cookie j to child i, and this child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum value.

Example 1:

Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have three children and two biscuits. The appetite values ​​of the three children are: 1, 2, 3.
Although you have two small biscuits, since their size is 1, you can only satisfy the child whose appetite is 1. So you should output 1.

Example 2:

Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have two children and three biscuits, and the appetite values ​​of the two children are 1,2, respectively.
The number and size of biscuits you have are enough to satisfy all children. So you should output 2.

prompt:

1 <= g.length <= 3 * 104
0 <= s.length <= 3 * 104
1 <= g[i], s[j] <= 231 - 1

Problem-solving ideas

how are you

Sort the appetite and size, and if s[i] is greater than the current g[j], distribute the biscuit to him until the traversal of s or g is completed.

Code

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        ans = 0
        while s and g:
            S = s.pop(0)
            if S >= g[0]:
                ans += 1
                g.pop(0)
        return ans

Guess you like

Origin blog.csdn.net/qq_36477513/article/details/111660487