Pattern visualizer
Assign Cookies
The greedy choice is to satisfy the least demanding child with the smallest cookie that suffices. Giving a large cookie to an easily satisfied child wastes size that could satisfy a greedier child later, while giving a cookie to a child who cannot be satisfied by it wastes the cookie. By sorting both greed factors and cookie sizes, we scan both arrays with two pointers: if the current cookie satisfies the current child, we match them and move both pointers forward; otherwise, this cookie is too small for anyone remaining, so we discard it and try the next larger cookie. Animated on: g = [1, 2, 3] (greed factors), s = [1, 1] (cookie sizes) — maximize the number of content children..
Greedy smallest-cookie to smallest-greed matching
Sort both arrays. Children g=[1,2,3] at indices 0–2, cookies s=[1,1] at indices 3–4. Start pointers at child=0 (greed 1) and cookie=0 (size 1).
1FUNCTION findContentChildren(g, s):2 sort g ascending, sort s ascending3 child = 0, cookie = 04 WHILE child < length of g and cookie < length of s:5 IF s[cookie] >= g[child]:6 move child one step forward7 move cookie one step forward8 RETURN child
← / → step · space play · Home restart