Minimum Limit of Balls in a Bag LeetCode solution in Java

1
class Solution {
2

3
public int minimumSize(int[] nums, int maxOperations) {
4
// initiate the boundary for possible answers, here if you let min=1 it will still work for most
5
// cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can
6
// choose to sort the array and make the max= arr.max, at the price of time consumption.
7
// The answer should be the minimized max value.
8
int min = 0;
9
int max = 1000000000;
10
// Compared with min<max or min <= max, min + 1 < max will avoid infinite loops e.g. when min =
11
// 2, max = 3
12
while (min + 1 < max) {
13
int mid = (max - min) / 2 + min;
14
// count indicates the operation times with atmost mid balls in bag.
15
int count = 0;
16
for (int a : nums) {
17
// this is the same as Math. ceil(a/mid) - 1=> math.ceil(a/mid) gives the number of divided
18
// bags, we subtract the number by 1 to get the subdivision operation times.
19
count += (a - 1) / mid;
20
}
21
// if count < maxOperations, max WOULD be further minimized and set to mid;
22
// if count = maxOperations, max still COULD be further minimized and set to mid.
23
// so we combine < and = cases together in one if condition
24
if (count <= maxOperations) {
25
// max = mid - 1 will not work in this case becasue mid could be the correct answer.
26
// To not miss the correct answer we set a relatively "loose" boundary for max and min.
27
max = mid;
28
} else {
29
min = mid;
30
}
31
}
32
// Now we find the minimized max value
33
return max;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0