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.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= candies.length <= 10^51 <= candies[i] <= 10^71 <= k <= 10^12
Solution
Method 1 - Using Binary Search
The problem involves distributing piles of candies to k children such that each child receives the same number of candies from a single pile. Since we can split the piles but cannot merge them, the objective is to find the maximum number x such that at least k piles of size x can be created. To solve this efficiently:
Approach
Binary Search:
- Use binary search to determine the maximum possible number
xof candies each child can receive. - Searching is performed in the range from
1tomax(candies), wheremax(candies)is the largest pile size. - For each candidate
x, check if it is possible (feasible) to distribute the candies such that at leastkchildren receive a pile of sizexor larger.
- Use binary search to determine the maximum possible number
Feasibility Check:
- For a given candidate
x, calculate how many children can be served. This is done by summing uppile // xfor all piles in thecandiesarray. - If the total number of children served is greater than or equal to
k, thenxis feasible.
- For a given candidate
Binary Search Adjustment:
- If
xis feasible, search for a largerx(right side of the binary search range). - Otherwise, search for a smaller
x(left side of the binary search range).
- If
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n*log(M)), wherenis the size of array andMis the max number of candles.- Binary search operates over the range
[1, max(candies)]with aroundlog(max(candies))iterations. - For each iteration, the feasibility check scans the
candiesarray (sizen) inO(n)time. - Total time complexity is
O(n * log(max(candies))).
- Binary search operates over the range
- 🧺 Space complexity:
O(1)