Maximum Candies Allocated to K Children, explained
To solve Maximum Candies Allocated to K Children, binary search on the share size: a share s works when the sum of pile // s over all piles is at least k. Larger shares serve fewer children, so the answer is the largest working share, found in O(n log M) time where M is the biggest pile, and it is 0 when even a share of 1 cannot reach every child.
By Evin JohnPublished 8 min read
What the problem asks
You have several piles of candy, given as a list of counts, and k children. You may break any pile into smaller sub-piles, but you may never pour two piles together. Each child receives at most one sub-pile, and every child must end up with exactly the same number of candies. Some candy can be left over, and some piles can go unused. Return the largest number of candies each child can get. If you cannot give every child at least one, return 0.
| Piles | Children | Largest share | Reasoning |
|---|---|---|---|
| [7, 3, 9] | 4 | 3 | Share 3 feeds 2 + 1 + 3 = 6 children; share 4 feeds only 1 + 0 + 2 = 3 |
| [8, 5] | 3 | 4 | 8 splits into two 4s, 5 gives one 4 with 1 left |
| [1, 100] | 2 | 50 | The tiny pile is ignored; 100 splits into two 50s |
| [6, 6, 6] | 3 | 6 | One whole pile per child |
| [2, 2] | 5 | 0 | Only 4 candies for 5 children |
The [8, 5] row is the one to talk through. The total is 13, and 13 // 3 = 4 suggests 4, which happens to work. But the total alone can mislead: with piles [3, 3, 3] and two children, the total says 4, yet no pile holds 4 candies, so the real answer is 3. Leftovers inside a pile cannot travel to another pile.
Questions to ask first: can k exceed the total number of candies, which makes the answer 0? How large can k and the pile sizes get? In the common statement k can be far larger than the number of piles, so sums need 64-bit integers in Java or C++.
What the interviewer is looking for
This is a clean test of whether you can spot a monotone feasibility function. If every child can receive s candies, every child can certainly receive s - 1, because any sub-pile of size s can be trimmed. So the shares that work form a prefix 1, 2, ..., best, and everything above best fails. The interviewer wants you to say that out loud, then write a search that does not go off by one at either end.
Slow approach: try every share
Count down from the largest pile. For each share s, a pile of size p can feed p // s children, so add that up across the piles. The first share whose count reaches k is the answer, and if nothing down to 1 works, return 0.
def max_candies_each_slow(piles, kids):
for share in range(max(piles), 0, -1):
if sum(p // share for p in piles) >= kids:
return share
return 0When the biggest pile holds ten million candies and there are a hundred thousand piles, this does up to a trillion divisions. It is correct, it is a fine opening line, and it is far too slow.
Main approach: search for the first share that fails
Because the working shares form a prefix, binary search finds the boundary in logarithmic steps. One tidy way to write it is to look for the smallest share that does not work. Set lo to 1 and hi to the largest pile plus one. The top value can never work, since no pile is that big, so it is a safe sentinel. At each step, test mid. If mid feeds at least k children, the boundary is above mid, so move lo to mid + 1. Otherwise mid already fails, so pull hi down to mid. When the bounds meet, lo is the first failing share and the answer is lo - 1.
This shape has two nice properties. The midpoint can round down safely because lo always moves past mid on success. And the 0 case falls out on its own: if share 1 fails, the loop ends with lo at 1 and returns 0 without a special branch.
def max_candies_each(piles, kids):
def feeds_everyone(share):
return sum(p // share for p in piles) >= kids
lo, hi = 1, max(piles) + 1 # hi never works
while lo < hi:
mid = (lo + hi) // 2
if feeds_everyone(mid):
lo = mid + 1
else:
hi = mid
return lo - 1function maxCandiesEach(piles, kids) {
const feedsEveryone = (share) => {
let served = 0;
for (const p of piles) {
served += Math.floor(p / share);
if (served >= kids) return true;
}
return false;
};
let lo = 1;
let hi = piles.reduce((a, b) => Math.max(a, b)) + 1;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (feedsEveryone(mid)) lo = mid + 1;
else hi = mid;
}
return lo - 1;
}The early return in the JavaScript check is worth mentioning. It keeps the running count small, which matters in languages where a sum of many large quotients could overflow, and it often stops the loop before the end of the array.
Walking through one input
Take piles [7, 3, 9] and four children. lo is 1 and hi is 10. mid = 5 feeds 1 + 0 + 1 = 2 children, too few, so hi becomes 5. mid = 3 feeds 2 + 1 + 3 = 6, enough, so lo becomes 4. mid = 4 feeds 1 + 0 + 2 = 3, too few, so hi becomes 4. Now lo equals hi at 4, the first failing share, and the function returns 3.
Time and space
| Method | Running time | Memory beyond input | Comment |
|---|---|---|---|
| Scan every share | O(n · M) | O(1) | Good for explaining, bad for big piles |
| Binary search on the share | O(n log M) | O(1) | Expected solution |
You can tighten hi to min(max pile, total // k) + 1, since no share can beat the average either. It saves a step or two of the search but does not change the bound, so only add it if you have time.
Inputs that break careless code
- More children than candies, such as [2, 2] with five children: the answer is 0, and your code must not divide by zero along the way. Starting lo at 1 keeps share 0 out of every check.
- A single pile: the answer is that pile // k.
- One huge pile beside many tiny ones: the tiny piles may be useless at the winning share, which is fine because unused piles are allowed.
- k equal to 1: the answer is simply the largest pile.
- Very large k with 32-bit integers in Java or C++: use long for k and for the running count.
Mistakes interviewers see often
- Using total // k as the answer. It ignores the rule that piles cannot be combined.
- Searching from 0 and dividing by mid when mid can be 0.
- Mixing two binary search templates, for example lo = mid with a rounded-down midpoint, which can loop forever.
- Returning lo instead of lo - 1 in the first-failure template, which is off by one on every input.
- Sorting the piles first. It costs O(n log n) and buys nothing, because the check does not care about order.
A sample explanation
Fictional example
- Candidate
- If each child can get s candies, each child can also get s minus 1, so the feasible shares are a prefix and I can binary search for where they stop.
- Candidate
- For a share s, a pile of p candies feeds p // s children, so the test is one pass that sums those quotients and compares with k.
- Candidate
- I search for the first share that fails between 1 and max pile plus one, return that minus one, and a result of 0 means not every child can get a candy.
Related walkthroughs
Divide Chocolate uses the same monotone argument, but its check is a greedy sweep over contiguous pieces rather than a sum of quotients. Minimum Time to Complete Trips flips the direction and hunts for the smallest value that works, with a check that looks almost identical to this one. The algorithm interview questions page covers binary search variants more broadly.
Rehearsing with Natively
Natively can read a problem statement from a screenshot during practice and propose an approach and code, which you can hold up against your own after a first attempt. Because it transcribes a mock round on your computer, you can also reread how you justified the search bounds and whether the 0 case came up. More on using an AI interview assistant on Mac and Windows.
Questions people ask
How do you solve Maximum Candies Allocated to K Children?
Binary search on the number of candies per child. A share s works if the sum of pile // s across all piles is at least k. Search between 1 and the largest pile, and return 0 if even a share of 1 fails.
Why can't I just divide the total candies by k?
Piles cannot be merged. Leftover candies in one pile cannot top up another, so the total over k can overstate the answer, as with piles [3, 3, 3] and two children, where the real answer is 3, not 4.
What is the time complexity?
O(n log M), where n is the number of piles and M is the largest pile. Each check is one pass over the piles and the search needs about log M checks. Extra space is O(1).
When is the answer 0?
When there are fewer candies in total than children, so not every child can get even one. Starting the search at 1 handles this without dividing by zero.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
