LeetCode 1283. Find the Smallest Divisor Given a Threshold (javascript solution)
codingpineapple
Posted on May 20, 2021
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
};
π πͺ π
π©
codingpineapple
Posted on May 20, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024