Maximum Candies Allocated to K Children - 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.

Input & Output

Example 1 — Basic Distribution
$ Input: candies = [5,8,6], k = 3
Output: 5
💡 Note: We can give 5 candies to each child: pile[0] gives 1 child (5÷5=1), pile[1] gives 1 child (8÷5=1), pile[2] gives 1 child (6÷5=1). Total = 3 children ≥ 3.
Example 2 — Multiple Children Per Pile
$ Input: candies = [2,5], k = 11
Output: 0
💡 Note: Maximum children we can satisfy is 2÷1 + 5÷1 = 7, which is less than 11. So each child gets 0 candies.
Example 3 — Optimal Split
$ Input: candies = [5,2,3], k = 4
Output: 2
💡 Note: Give 2 candies each: pile[0] gives 2 children (5÷2=2), pile[1] gives 1 child (2÷2=1), pile[2] gives 1 child (3÷2=1). Total = 4 children.

Constraints

  • 1 ≤ candies.length ≤ 105
  • 1 ≤ candies[i] ≤ 107
  • 1 ≤ k ≤ 1012

Visualization

Tap to expand
Maximum Candies Allocated to K Children INPUT Candy Piles Array 5 Pile 0 8 Pile 1 6 Pile 2 candies = [5, 8, 6] k = 3 children Children to allocate: ALGORITHM STEPS 1 Binary Search Setup low=1, high=max(candies)=8 2 Try mid = 4 5/4+8/4+6/4 = 1+2+1 = 4 4 >= 3 (OK) --> try higher 3 Try mid = 6 5/6+8/6+6/6 = 0+1+1 = 2 2 < 3 (FAIL) --> try lower 4 Try mid = 5 5/5+8/5+6/5 = 1+1+1 = 3 3 >= 3 (OK) --> answer! Binary Search Range: 1 5 8 count = sum(pile/mid) if count >= k: valid FINAL RESULT Maximum candies per child: 5 Allocation Distribution: Child 1: 5 Child 2: 5 C3: 5 Pile Breakdown: Pile 0 (5): 1 child x 5 Pile 1 (8): 1 child x 5 (+3 left) Pile 2 (6): 1 child x 5 (+1 left) Output: 5 Key Insight: Binary search on the answer! Instead of trying all possible candy amounts, use binary search on range [1, max(candies)]. For each candidate value mid, check if we can allocate at least k portions of size mid from all piles combined. Time Complexity: O(n * log(max)) where n = number of piles. This is much faster than brute force O(n * max). TutorialsPoint - Maximum Candies Allocated to K Children | Binary Search Approach
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen