Loading problems...
TL;DR: The optimal solution utilizes binary search on the answer space (the number of candies per child) to find the maximum value that satisfies the allocation constraint for k children.
The problem asks us to determine the maximum number of candies that can be allocated to each of k children. We are given an array candies representing pile sizes. We can split piles but cannot merge them. Each child must receive an identical number of candies from a single pile. If the total number of candies is insufficient to give even 1 candy to k children, the answer is 0.
This problem, "Maximum Candies Allocated to K Children" (LeetCode 2226), is a classic optimization problem that transforms into a decision problem: "Can we give every child x candies?"
The naive approach involves checking every possible number of candies a child could receive, starting from the largest possible value down to 1.
candies array (or strictly, the sum of all candies divided by ).kx, iterate through the candies array to calculate how many children can be served.p, we can serve floor(p / x) children.k, then x is the maximum possible value (since we started from the top). Return x.Pseudo-code:
textmax_candies = max(candies) for x from max_candies down to 1: count = 0 for pile in candies: count += pile / x if count >= k: return x return 0
Complexity Analysis:
The time complexity is , where is the length of the candies array and is the maximum value in candies (up to ).
With and , the total operations could reach , which far exceeds the standard time limit of roughly operations per second. This approach results in a Time Limit Exceeded (TLE) error.
The key intuition is observing the monotonic nature of the "validity" function.
Let canAllocate(x) be a boolean function that returns true if it is possible to give x candies to k children, and false otherwise.
x candies, it is certainly possible to give them x - 1 candies (we simply have leftovers).x candies, it is certainly impossible to give them x + 1 candies (we cannot create matter).This monotonicity allows us to discard half of the search space at every step. Instead of linearly scanning values, we can pick a middle value mid.
canAllocate(mid) is true, then mid is a candidate solution, and we should try to find a larger valid number in the upper half [mid + 1, right].canAllocate(mid) is false, then mid is too large, and we must search in the lower half [left, mid - 1].Visual Description:
Imagine the number line from 0 to the maximum pile size. The function canAllocate(x) will return true for a prefix of this number line (e.g., 1, 2, 3... ans) and false for the suffix (ans+1 ... max). Our goal is to find the boundary where true transitions to false. Binary search efficiently converges on this boundary.

Let candies = [5, 8, 6] and k = 3.
Initialization:
left = 1right = 8 (max of candies)ans = 0Iteration 1:
mid = (1 + 8) / 2 = 4mid = 4:
5 / 4 = 1 child.8 / 4 = 2 children.6 / 4 = 1 child.mid is valid.ans = 4left becomes 5.Iteration 2:
left = 5, right = 8mid = (5 + 8) / 2 = 6mid = 6:
mid is invalid (too high).right becomes 5.Iteration 3:
left = 5, right = 5mid = (5 + 5) / 2 = 5mid = 5:
mid is valid.ans = 5left becomes 6.Termination:
left = 6, right = 5. Loop terminates.ans = 5.The correctness relies on the Monotonicity Property. Let be the maximum number of children we can serve with candies each. . Since is a non-increasing function with respect to (as increases, the result stays same or decreases), the sum is also non-increasing. Therefore, the boolean predicate is monotonic. Specifically, there exists a threshold such that for all , is true, and for all , is false. Binary search is proven to find this threshold in logarithmic steps.
cpp#include <vector> #include <algorithm> #include <numeric> class Solution { public: int maximumCandies(std::vector<int>& candies, long long k) { int left = 1; int right = 0; // Determine the search space upper bound for (int candy : candies) { right = std::max(right, candy); } int ans = 0; while (left <= right) { int mid = left + (right - left) / 2; // Check if 'mid' candies per child is feasible long long childrenServed = 0; for (int candy : candies) { childrenServed += candy / mid; } if (childrenServed >= k) { ans = mid; // mid is a valid candidate left = mid + 1; // Try to find a larger valid amount } else { right = mid - 1; // mid is too large } } return ans; } };
javaclass Solution { public int maximumCandies(int[] candies, long k) { int left = 1; int right = 0; // Determine the search space upper bound for (int candy : candies) { right = Math.max(right, candy); } int ans = 0; while (left <= right) { int mid = left + (right - left) / 2; // Check if 'mid' candies per child is feasible long childrenServed = 0; for (int candy : candies) { childrenServed += candy / mid; } if (childrenServed >= k) { ans = mid; // mid is a valid candidate left = mid + 1; // Try to find a larger valid amount } else { right = mid - 1; // mid is too large } } return ans; } }
pythonclass Solution: def maximumCandies(self, candies: List[int], k: int) -> int: left, right = 1, max(candies) ans = 0 while left <= right: mid = (left + right) // 2 # Calculate total children that can be served with 'mid' candies children_served = sum(candy // mid for candy in candies) if children_served >= k: ans = mid # mid is a valid candidate left = mid + 1 # Try to find a larger valid amount else: right = mid - 1 # mid is too large return ans
Time Complexity:
candies.length).max(candies)), which is up to .Space Complexity:
left, right, mid, count) for storage. The space used does not scale with the input size.The Binary Search on Answer pattern is highly reusable. The following problems share the exact same structure: we are looking for an integer x where a condition check(x) is monotonic.
h hours.In all these cases, replace the canAllocate logic with the specific problem's constraint check, but keep the binary search framework identical.
Q: Why do I get a "Division by Zero" error?
left = 0 in the binary search range without handling the division logic separately.candy / mid, if mid is 0, the program crashes.Q: Why does my solution fail on large inputs even with Binary Search?
int) to accumulate the count of children served.candies length is and values are up to . While the sum of children won't exceed the total candies, can be up to . The accumulation variable must be able to compare against .kklong long (C++) or long (Java).Q: Why do I get Time Limit Exceeded (TLE) with the correct logic?
left = mid without adjusting mid calculation to ceil.left = 1 and right = 2, mid becomes 1. If 1 is valid and you set left = mid, left remains 1, causing an infinite loop.left = mid + 1 and right = mid - 1 pattern for clarity and safety.