Fair Distribution of Cookies - Problem

You are given an integer array cookies, where cookies[i] denotes the number of cookies in the i-th bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to.

All the cookies in the same bag must go to the same child and cannot be split up.

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

Return the minimum unfairness of all distributions.

Input & Output

Example 1 — Basic Distribution
$ Input: cookies = [8,15,10,20,8], k = 2
Output: 31
💡 Note: Optimal distribution: Child 1 gets [8,15,8] = 31, Child 2 gets [10,20] = 30. Maximum is 31.
Example 2 — Equal Distribution
$ Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
💡 Note: One optimal way: Child 1: [6,1] = 7, Child 2: [3,2,2] = 7, Child 3: [4,1,2] = 7. All children get 7 cookies.
Example 3 — Single Large Bag
$ Input: cookies = [1,1,1,1,20], k = 2
Output: 20
💡 Note: Child 1 gets [1,1,1,1] = 4, Child 2 gets [20] = 20. The large bag determines the minimum unfairness.

Constraints

  • 2 ≤ cookies.length ≤ 8
  • 1 ≤ cookies[i] ≤ 105
  • 2 ≤ k ≤ cookies.length

Visualization

Tap to expand
Fair Distribution of Cookies INPUT cookies array (5 bags): 8 [0] 15 [1] 10 [2] 20 [3] 8 [4] k = 2 children: C1 C2 cookies = [8,15,10,20,8] k = 2 Total cookies: 61 Goal: Minimize max per child ALGORITHM STEPS 1 Sort Descending [20,15,10,8,8] for better pruning efficiency 2 Try Each Assignment For each bag, try giving to each child (backtrack) 3 Prune Branches Skip if current max >= best found so far 4 Track Minimum Update best unfairness when all bags assigned Backtracking Tree (simplified) pruned FINAL RESULT Optimal Distribution: C1 8 15 8 = 31 C2 10 20 = 30 Minimum Unfairness: 31 max(31, 30) = 31 Key Insight: Backtracking explores all possible distributions by trying to assign each cookie bag to each child. Pruning is critical: if a partial assignment already exceeds the best found answer, we skip that branch. Sorting cookies in descending order helps prune earlier by making large differences appear sooner in the search. TutorialsPoint - Fair Distribution of Cookies | Backtracking with Pruning
Asked in
Google 25 Amazon 18 Facebook 15
23.4K Views
Medium Frequency
~35 min Avg. Time
856 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