forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumCandiesAllocatedToKChildren.java
More file actions
44 lines (35 loc) · 1.33 KB
/
MaximumCandiesAllocatedToKChildren.java
File metadata and controls
44 lines (35 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package binary_search;
/**
* Description: https://leetcode.com/problems/maximum-candies-allocated-to-k-children
* Difficulty: Medium
* Time complexity: O(n log(Integer.MAX_VALUE))
* Space complexity: O(1)
*/
public class MaximumCandiesAllocatedToKChildren {
public int maximumCandies(int[] candies, long children) {
int minAllocation = 0;
int maxAllocation = Integer.MAX_VALUE;
// Possible optimization:
// int maxAllocation = Arrays.stream(candies).max().getAsInt();
int max = 0;
while (minAllocation <= maxAllocation) {
int midAllocation = minAllocation + (maxAllocation - minAllocation) / 2;
if (canAllocateCandyToEveryChild(candies, children, midAllocation)) {
max = minAllocation;
minAllocation = midAllocation + 1;
} else {
maxAllocation = midAllocation - 1;
}
}
return max;
}
private boolean canAllocateCandyToEveryChild(int[] candies, long totalChildren, int candiesPerChild) {
if (candiesPerChild == 0) return true;
long childrenWithCandies = 0;
for (int pile : candies) {
childrenWithCandies += pile / candiesPerChild;
if (childrenWithCandies >= totalChildren) return true;
}
return false;
}
}