#2226
Medium Algorithms Maximum candies allocated to k children
Array Binary Search
49.9% acceptance
Feb 25, 2026
1820
83
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn maximum_candies(candies: Vec<i32>, k: i64) -> i32 {
let total: i64 = candies.iter().map(|&c| c as i64).sum();
if total < k { return 0; }
let mut lo = 1i64;
let mut hi = candies.iter().max().copied().unwrap_or(0) as i64;
while lo < hi {
let mid = (lo + hi + 1) / 2;
let count: i64 = candies.iter().map(|&c| c as i64 / mid).sum();
if count >= k { lo = mid; } else { hi = mid - 1; }
}
lo as i32
}
}