DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1283. Find the Smallest Divisor Given a Threshold (javascript solution)

Description:

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

It is guaranteed that there will be an answer.

Solution:

Time Complexity : O(nlog(n))
Space Complexity: O(1)

// Binary search
var smallestDivisor = function(nums, threshold) {
    // Add result of each item in nums divied by mid to sum and check if sum <= threshold
    function checkCondition(mid){
        let sum = 0
        for(const num of nums) {
            sum+=Math.ceil(num/mid)
        }
        return sum <= threshold
    }
    // Lowest possible number can be 1 and the highest number can be the max of nums
    let left = 1, right = Math.max(...nums) 
    // Binary search template
    while(left < right) {
        const mid = left + Math.floor((right-left)/2)
        if(checkCondition(mid)) right = mid
        else left = mid+1
    }
    return left
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)