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^5
1 <= candies[i] <= 10^7
1 <= 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
x
of candies each child can receive. - Searching is performed in the range from
1
tomax(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 leastk
children receive a pile of sizex
or 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 // x
for all piles in thecandies
array. - If the total number of children served is greater than or equal to
k
, thenx
is feasible.
- For a given candidate
-
Binary Search Adjustment:
- If
x
is 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))
, wheren
is the size of array andM
is 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
candies
array (sizen
) inO(n)
time. - Total time complexity is
O(n * log(max(candies)))
.
- Binary search operates over the range
- 🧺 Space complexity:
O(1)