[LeetCode] Maximum Candies Allocated to K Children

2226. Maximum Candies Allocated to K Children

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 take at most one pile of candies and some piles of candies may go unused.

Return the maximum number of candies each child can get.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maximumCandies(vector<int>& c, long long k) {
int l = 1, r = *max_element(begin(c), end(c)), res = 0;
while(l <= r) {
int m = l + (r-l)/2;
long long sum = 0;
for(auto& n : c) {
sum += (n / m);
}
if(sum < k) {
r = m - 1;
} else {
l = m + 1;
res = max(res, m);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/maximum-candies-allocated-to-k-children/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.