Maximum Candies Allocated to K Children - Problem

You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.

You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can be allocated candies from only one pile of candies and some piles of candies may go unused.

Return the maximum number of candies each child can get.

Input & Output

Example 1 — Basic Distribution
$ Input: candies = [5,8,6], k = 3
Output: 5
💡 Note: We can give 5 candies to each child: pile[0] gives 1 child (5÷5=1), pile[1] gives 1 child (8÷5=1), pile[2] gives 1 child (6÷5=1). Total = 3 children ≥ 3.
Example 2 — Multiple Children Per Pile
$ Input: candies = [2,5], k = 11
Output: 0
💡 Note: Maximum children we can satisfy is 2÷1 + 5÷1 = 7, which is less than 11. So each child gets 0 candies.
Example 3 — Optimal Split
$ Input: candies = [5,2,3], k = 4
Output: 2
💡 Note: Give 2 candies each: pile[0] gives 2 children (5÷2=2), pile[1] gives 1 child (2÷2=1), pile[2] gives 1 child (3÷2=1). Total = 4 children.

Constraints

  • 1 ≤ candies.length ≤ 105
  • 1 ≤ candies[i] ≤ 107
  • 1 ≤ k ≤ 1012

Visualization

Tap to expand
Maximum Candies Per Child: [5,2,3], k=4523Pile 1Pile 2Pile 3Need to distribute to k=4 children equallyChild 1Child 2Child 3Child 4Answer: 2 candies per child5÷2 + 2÷2 + 3÷2 = 2+1+1 = 4 children
Understanding the Visualization
1
Input
Array of candy piles and number of children k
2
Process
Binary search for maximum candies per child
3
Output
Maximum candies each child can receive equally
Key Takeaway
🎯 Key Insight: Use binary search on answer space - if x candies work, then any amount < x also works
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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