Maximum Candies Allocated to K Children: Binary Search Solution Explained
The maximum candies allocated to k children problem asks you to find the largest number of candies that can be given to each child when every child must receive the same amount. You may split any pile into smaller sub-piles, but you cannot merge two piles together. You are given an array of candy piles and an integer k. Each child can receive at most one sub-pile, and some candy may remain unused.
the maximum number of candies per child that can be distributed under these rules.
A direct search over every possible candy count would be too slow because the answer can range from 0 to the largest pile size. But instead, we can binary search on the answer. The key observation is monotonicity: if it is possible to give every child x candies, then it is also possible to give every child any smaller amount. Conversely, if x candies per child cannot be distributed, then no larger amount can be distributed either It's one of those things that adds up..
For a candidate amount x, we count how many children can receive x candies by summing pile // x over every pile. Integer division is valid because each pile can be split into sub-piles of size x, and any leftover candies in that pile are simply unused. But if the total number of sub-piles is at least k, then x is feasible, so we try a larger value. Otherwise, we try a smaller value It's one of those things that adds up..
Easier said than done, but still worth knowing.
A typical implementation looks like this:
def maximumCandies(candies, k):
if k == 0:
return 0
low, high = 0, max(candies)
while low < high:
mid = (low + high + 1) // 2
children = 0
for pile in candies:
children += pile // mid
if children >= k:
break
if children >= k:
low = mid
else:
high = mid - 1
return low
The upper midpoint (low + high + 1) // 2 is important here because we are searching for the largest feasible value. Using the lower midpoint can cause an infinite loop when low and high are adjacent.
The time complexity is O(n log M), where n is the number of candy piles and M is the size of the largest pile. Day to day, the binary search performs O(log M) iterations, and each feasibility check scans the piles in O(n) time. The extra space usage is O(1).
No fluff here — just what actually works.
This approach avoids constructing sub-piles explicitly and checks only whether a proposed allocation is possible. By narrowing the search range based on that feasibility test, it efficiently finds the maximum number of candies that can be given to each of the k children.