1283. Find the Smallest Divisor Given a Threshold

https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/

找一个能让数组内每个元素对它倍数(余数不为0时往上取整)的和小于等于threshold的最小整数。答案的取值范围为[1, max(nums)],二分范围,当倍数和大于threshold时说明当前取的太小,start + 1。

class Solution {
public:
    int smallestDivisor(vector<int>& nums, int threshold) {
        const auto cal = [&](int t) {
            int r = 0;
            for (const auto num : nums) {
                r += num / t + (num % t == 0 ? 0 : 1);
            }
            return r;
        };
        int start = 1, end = 1;
        for (int i = 0; i < nums.size(); ++i) {
            end = max(end, nums[i]);
        }
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (cal(mid) > threshold) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        return start;
    }
};

Last updated