Created
December 7, 2024 17:40
-
-
Save igavrysh/4c1ba97702948b2bbf2fd7fe3f6e6f9e to your computer and use it in GitHub Desktop.
1760. Minimum Limit of Balls in a Bag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
1760. Minimum Limit of Balls in a Bag | |
Medium | |
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 | |
*/ | |
class Solution { | |
public int minimumSize(int[] nums, int maxOperations) { | |
int n = nums.length; | |
int bad = 0; | |
int good = (int)Math.pow(10, 9); | |
while (good - bad > 1) { | |
int m = bad + (good - bad) / 2; | |
int curr_ops = 0; | |
for (int i = 0; i < n; i++) { | |
if (nums[i] > m) { | |
curr_ops += (nums[i] - 1) / m; | |
} | |
if (curr_ops > maxOperations) { | |
break; | |
} | |
} | |
if (curr_ops > maxOperations) { | |
bad = m; | |
} else { | |
good = m; | |
} | |
} | |
return good; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment