Chocolate Distribution Problem
Sort, then slide a fixed window of m packets
Fairness here is one number: largest packet handed out minus smallest. Sorting turns the search into a much smaller one, because in sorted order the m packets closest in size are always next to each other — reaching past a packet to grab a further one can only stretch the gap. So slide a window of exactly m packets across the sorted list; the difference between its two ends is that group's spread, and the smallest spread seen wins.
Details
Animated on: packets = 21, 3, 8, 5, 13, 17, 19, 30 and m = 4 students — hand one packet to each student so the biggest packet given out minus the smallest is as small as possible.
Problem:Chocolate Distribution ProblemEasy
Sort, then slide a fixed window of m packets
step 1 / 8
8 packets 21, 3, 8, 5, 13, 17, 19, 30 to hand out to 4 students, one packet each. We want the group of 4 where the biggest and smallest packet are as close as possible.
1FUNCTION minSpread(packets, m):2 packets <- SORT(packets)3 best <- INFINITY4 FOR i <- 0 TO LENGTH(packets) - m5 j <- i + m - 16 spread <- packets[j] - packets[i]7 IF spread < best8 best <- spread9 RETURN best
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- 8 packets 21, 3, 8, 5, 13, 17, 19, 30 to hand out to 4 students, one packet each. We want the group of 4 where the biggest and smallest packet are as close as possible.
- Sorted: 3, 5, 8, 13, 17, 19, 21, 30. Now the 4 closest-sized packets must sit side by side — skipping a packet to reach a further one only pulls the biggest and smallest further apart, never closer.
- Window 3, 5, 8, 13: largest 13 minus smallest 3 = 10. No group has been measured yet, so 10 is the spread to beat.
- Window 5, 8, 13, 17: largest 17 minus smallest 5 = 12. 12 is wider than the best spread so far (10), so this group is discarded — one student would do noticeably better than another.
- Window 8, 13, 17, 19: largest 19 minus smallest 8 = 11. 11 is wider than the best spread so far (10), so this group is discarded — one student would do noticeably better than another.
- Window 13, 17, 19, 21: largest 21 minus smallest 13 = 8. 8 beats the best spread so far (10), so these 4 packets are the fairest split we have found.
- Window 17, 19, 21, 30: largest 30 minus smallest 17 = 13. 13 is wider than the best spread so far (8), so this group is discarded — one student would do noticeably better than another.
- Every window of 4 has been measured. Give out 13, 17, 19, 21 — the smallest possible gap between the luckiest and unluckiest student is 8.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.