From LeetCode 455. Assign Cookies

Description

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

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.

Solution

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        # first we think of optimize cookie
        g.sort()
        s.sort()
        res = 0
        for i in range(len(s)):
            if res < len(g) and s[i] >= g[res]:
                res += 1
        
        return res
    
    def findContentChildren1(self, g: List[int], s: List[int]) -> int:
        # feed greatest greed factor
        g.sort()
        s.sort()
        
        start, count = len(s) - 1, 0
        for index in range(len(g)-1, -1, -1):
            if start >= 0 and g[index] <= s[start]:
                start -= 1
                count += 1
        return count