2024-12-07 Daily Challenge

Today I have done leetcode's December LeetCoding Challenge with cpp.

December LeetCoding Challenge 7

Description

Minimum Limit of Balls in a Bag

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.
    <ul>
    	<li>For example, a bag of <code>5</code> balls can become two new bags of <code>1</code> and <code>4</code> balls, or two new bags of <code>2</code> and <code>3</code> balls.</li>
    </ul>
    </li>
    

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 <= 105
  • 1 <= maxOperations, nums[i] <= 109

Solution

class Solution {
  bool check(vector<int> &nums, int penalty, int maxOperations) {
    for(auto n : nums) {
      maxOperations -= (n / penalty) + !!(n % penalty) - 1;
    }
    return maxOperations >= 0;
  }
public:
  int minimumSize(vector<int>& nums, int maxOperations) {
    int low = 1;
    int high = *max_element(nums.begin(), nums.end());

    while(low < high) {
      int mid = (low + high) / 2;
      if(check(nums, mid, maxOperations)) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return high;
  }
};

// Accepted
// 58/58 cases passed (30 ms)
// Your runtime beats 78.22 % of cpp submissions
// Your memory usage beats 22.28 % of cpp submissions (59.8 MB)