Leetcode-1283

Find the Smallest Divisor Given a Threshold

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
36
37
38
39
#include <iostream>
#include <vector>

class Solution {
public:
    int smallestDivisor(std::vector<int>& nums, int threshold) {
        long long sum = 0;
        int right = 0;
        for (int i : nums) {
            sum += i;
            right = std::max(right, i);
        }
        int left = sum / threshold;
        if (!left) {
            return 1;
        }
        
        for (int mid = (left + right) / 2; right > left; mid = (left + right) / 2) {
            int k = getSum(nums, mid);
            if (k > threshold) {
                left = mid + 1;
            }
            else {
                right = mid;
            }
        }
        
        return left;
    }
    
private:
    int getSum(std::vector<int>& nums, int divisor) {
        int sum = nums.size();
        for (int num : nums) {
            sum += (num - 1) / divisor;
        }
        return sum;
    }
};

Leetcode-1283