LeetCode/cs/minimum-limit-of-balls-in-a-bag.cs

39 lines
930 B
C#

public class Solution {
private int CeilDiv(int left, int right) {
if (left % right != 0) {
return 1 + left / right;
}
return left / right;
}
private bool IsPossible(int[] nums, int maxOperations, int maxBalls) {
var performed = 0;
foreach (var bag in nums) {
var operations = CeilDiv(bag, maxBalls) - 1;
performed += operations;
if (performed > maxOperations) {
return false;
}
}
return true;
}
public int MinimumSize(int[] nums, int maxOperations) {
int left = 1, right = nums.Max();
while (left < right) {
var middle = (left + right) / 2;
if (IsPossible(nums, maxOperations, middle)) {
right = middle;
} else {
left = middle + 1;
}
}
return left;
}
}