Skip to content

Commit e539ef1

Browse files
authored
Create maximum-candies-allocated-to-k-children.cpp
1 parent 8f67406 commit e539ef1

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(nlogr), r is max(candies)
2+
// Space: O(1)
3+
4+
// binary search
5+
class Solution {
6+
public:
7+
int maximumCandies(vector<int>& candies, long long k) {
8+
const auto& check = [&candies, &k](const auto& x) {
9+
return accumulate(cbegin(candies), cend(candies), 0ll,
10+
[&x](const auto& total, const auto& v) {
11+
return total + v / x;
12+
}) >= k;
13+
};
14+
int left = 1, right = *max_element(cbegin(candies), cend(candies));
15+
while (left <= right) {
16+
const auto& mid = left + (right - left) / 2;
17+
if (!check(mid)) {
18+
right = mid - 1;
19+
} else {
20+
left = mid + 1;
21+
}
22+
}
23+
return right;
24+
}
25+
};

0 commit comments

Comments
 (0)