Assign Cookies
LeetCode 455 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Sort both; smallest sufficient cookie per child.
నేను Assign Cookies (LeetCode 455) ను ఇలా పరిష్కరించాను — Sorting + Simple Greedy ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.
Approach
- 1
Sort g and s.
- 2
If the current cookie satisfies the current child, count it and move to the next child.
- 3
Always move to the next cookie.
నేను ఎలా పరిష్కరించాను
Greedy two pointersPythonO(n log n) time
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
student=0
i=0
j=0
while i<len(g) and j<len(s):
if s[j]>=g[i]:
student+=1
i+=1
j+=1
return student
Assign Cookies — తరచూ అడిగే ప్రశ్నలు
Assign Cookies వెనుక ఉన్న intuition ఏమిటి?
Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.
Assign Cookies (LeetCode 455) ను ఎలా పరిష్కరించాలి?
1. Sort g and s. 2. If the current cookie satisfies the current child, count it and move to the next child. 3. Always move to the next cookie.
Assign Cookies యొక్క time, space complexity ఎంత?
Time: O(n log n + m log m). Space: O(1). (Accepted approach: Greedy two pointers.)
Assign Cookies లో సాధారణ పొరపాట్లు ఏమిటి?
Skip cookies that are too small rather than skipping children.