Fair Distribution of Cookies - Problem

Imagine you're a parent trying to fairly distribute bags of cookies among your children for a school event. You have several bags, each containing different amounts of cookies, and you need to give all bags to your k children.

Here's the challenge: each bag must go to exactly one child (you can't split a bag), and you want to minimize the maximum number of cookies any single child receives. This creates the most "fair" distribution possible.

Given an integer array cookies where cookies[i] represents the number of cookies in the i-th bag, and an integer k representing the number of children, return the minimum possible unfairness.

The unfairness is defined as the maximum total cookies obtained by any single child in the distribution.

Input & Output

example_1.py โ€” Basic Distribution
$ Input: cookies = [8,15,10,20,8], k = 2
โ€บ Output: 31
๐Ÿ’ก Note: One optimal distribution is [8,15,8] and [10,20]. Child 1 gets 31 cookies, child 2 gets 30 cookies. The unfairness is max(31,30) = 31.
example_2.py โ€” Equal Distribution
$ Input: cookies = [6,1,3,2,2,4,1,2], k = 3
โ€บ Output: 7
๐Ÿ’ก Note: One optimal distribution is [6,1], [3,2,2] and [4,1,2]. Each child gets 7 cookies, so unfairness is 7.
example_3.py โ€” Single Large Bag
$ Input: cookies = [1,1,1,100], k = 2
โ€บ Output: 100
๐Ÿ’ก Note: The large bag of 100 cookies must go to one child, so minimum unfairness is 100. Best distribution: [1,1,1] and [100].

Visualization

Tap to expand
Cookie Bags81510Child 123Child 230Goal: Minimize max(23, 30) = 30๐ŸŽฏ Unfairness = 30
Understanding the Visualization
1
Start with empty hands
All children start with 0 cookies
2
Pick up first bag
Decide which child gets this bag of cookies
3
Try all possibilities
Recursively try giving each remaining bag to each child
4
Track the 'luckiest' child
Keep track of maximum cookies any child has
5
Find minimum unfairness
Return the distribution where the luckiest child has minimum cookies
Key Takeaway
๐ŸŽฏ Key Insight: Use backtracking with early pruning - if current distribution already exceeds our best answer, abandon that path immediately to dramatically reduce search space.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(k^n)

For each of n bags, we try k children, leading to k^n total combinations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Recursion stack depth equals number of bags

n
2n
โšก Linearithmic Space

Constraints

  • 2 โ‰ค cookies.length โ‰ค 8
  • 1 โ‰ค cookies[i] โ‰ค 105
  • 2 โ‰ค k โ‰ค cookies.length
  • All bags must be distributed - no bag can be left unassigned
Asked in
Google 45 Amazon 38 Microsoft 28 Meta 22
21.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen