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.