Maximum Candies Allocated to K Children

You are given an integer array `candies` where `candies[i]` is the size of pile `i`. You may split any pile into smaller sub-piles, but you cannot merge piles. Give each of `k` children one pile, and every child must get the same number of candies (some piles may go unused). Return the largest number of candies each child can get, or 0 if it is impossible to give every child at least one candy.

30:00

Maximum Candies Allocated to K Children
medium
Free written solution
Topics
Companies

You are given an integer array candies where candies[i] is the size of pile i. You may split any pile into smaller sub-piles, but you cannot merge piles. Give each of k children one pile, and every child must get the same number of candies (some piles may go unused). Return the largest number of candies each child can get, or 0 if it is impossible to give every child at least one candy.

Example 1:
Input: {"candies":[5,8,6],"k":3}
Output: 5
Constraints:
  • 1≤candies.length≤1051 \leq candies.\text{length} \leq 10^5

  • 1≤candies[i]≤1071 \leq candies[i] \leq 10^7

  • 1≤k≤10121 \leq k \leq 10^{12} (here k fits in a 32-bit int)

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"candies":[5,8,6],"k":3}

candy piles

5

.

8

.

6

.

candies per child (search range)

0lo 0 . hi 88

k = 3 children

Each child gets between 0 and 8 candies (a share can never beat the biggest pile). Binary search that range for the largest share that still serves 3 children.

Variables
VariableValue
k3
lo0
hi8
DepthFunction Call
Stack empty
0/10