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.