Minimum Limit of Balls in a Bag LeetCode solution in C++

1
class Solution {
2
public:
3
bool isPossible(vector<int> &nums, int mid_penalty, int maxOperations) {
4
int operations = 0;
5

6
for (int i = 0; i < nums.size(); i++) {
7
operations += (nums[i] / mid_penalty); // Operations Nedded to divide that element.
8
if (nums[i] % mid_penalty == 0) // if it is completely divisible means
9
// less 1 less is needed for that nums.
10
operations--;
11
}
12

13
return operations <= maxOperations ? 1 : 0; // If operations are less than maxOperations it is
14
// one of our ans.
15
}
16
int minimumSize(vector<int> &nums, int maxOperations) {
17
int low_penalty = 1, high_penalty = *max_element(nums.begin(), nums.end());
18
int ans = high_penalty;
19
while (low_penalty <= high_penalty) {
20
int mid_penalty = low_penalty + (high_penalty - low_penalty) / 2;
21
if (mid_penalty == 0) // To avoid divison by zero.
22
break;
23
if (isPossible(nums, mid_penalty, maxOperations)) {
24
ans = mid_penalty;
25
high_penalty = mid_penalty - 1;
26
} else
27
low_penalty = mid_penalty + 1;
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0