Skip to content

Commit

Permalink
Runtime 28 ms , Memory 59.62 MB
Browse files Browse the repository at this point in the history
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.

You can perform the following operation at most maxOperations times:

Take any bag of balls and divide it into two new bags with a positive number of balls.
For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

Return the minimum possible penalty after performing the operations.

 

Example 1:

Input: nums = [9], maxOperations = 2
Output: 3
Explanation: 
- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
Example 2:

Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
Explanation:
- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.
 

Constraints:

1 <= nums.length <= 10^5
1 <= maxOperations, nums[i] <= 10^9
  • Loading branch information
risitadas authored Dec 7, 2024
1 parent 97608c2 commit 62ba8c2
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 1760. Minimum Limit of Balls in a Bag
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public int minimumSize(int[] nums, int maxOperations)
{

int l = 1;
int r = Arrays.stream(nums).max().getAsInt();

while (l < r)
{
int m = (l + r) / 2;
if(numOperations(nums, m) <= maxOperations)
{
r = m;
}
else
{
l = m + 1;
}

}

return l;

}


public int numOperations(int[] nums, int m)
{
int operations = 0;
for(int num : nums)
operations += (num - 1) / m;

return operations;
}

}

0 comments on commit 62ba8c2

Please sign in to comment.