DEV Community

codingpineapple
codingpineapple

Posted on

1 1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay