Leetcode-1760

Minimum Limit of Balls in a Bag

Time complexity: $O(n\log M)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>

class Solution {
public:
    int minimumSize(std::vector<int>& nums, int maxOperations) {
        int left = 1, right = 0;
        for (int n : nums) {
            right = std::max(n, right);
        }
        
        for (int mid = (left + right) / 2; right >= left;) {
            if (check(nums, maxOperations, mid)) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
            mid = (left + right) / 2;
        }
        
        return left;
    }
    
private:
    bool check(std::vector<int>& nums, int maxOperations, int num) {
        for (int n : nums) {
            maxOperations -= (n - 1) / num;
            if (maxOperations < 0) {
                return false;
            }
        }
        return true;
    }
};

Leetcode-1760