-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassignCookies.py
More file actions
28 lines (23 loc) · 1.24 KB
/
Copy pathassignCookies.py
File metadata and controls
28 lines (23 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# DATE 2025/08/31
"""
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
Greedy Algorithm
Sort both arrays. Iterate over both arrays with two pointers. If the current cookie can satisfy the current child (s[j] >= g[i]), we move to the next child (i += 1). In any case, we move to the next cookie (j += 1). The number of satisfied children is given by the pointer i.
- Time Complexity: O(n log n + m log m) due to sorting, where n is the number of children and m is the number of cookies.
- Space Complexity: O(1)
"""
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
if len(s) == 0:
return 0
g.sort()
s.sort()
i = 0
j = 0
while i < len(g) and j < len(s):
if s[j] >= g[i]:
i += 1
j += 1
return i