Search for a command to run...
Initialization
Divide every element by a candidate divisor, rounding each up, and add the results. A bigger divisor can only shrink that sum, so the sums are monotonic — which is exactly what lets binary search apply to the divisor itself.
Binary Search on the Answer
1function sumByD(nums, limit) {2 const n = nums.length;3 let sum = 0;4 for (let i = 0; i < n; i++) {5 sum += Math.ceil(nums[i] / limit);6 }7 return sum;8}9 10function smallestDivisor(nums, limit) {11 const n = nums.length;//low: 1high: 512 if (n > limit) return -1;13 14 let low = 1, high = Math.max(...nums);15 16 while (low <= high) {17 const mid = Math.floor((low + high) / 2);18 19 // Within budget — try an even smaller divisor20 if (sumByD(nums, mid) <= limit) {21 high = mid - 1;22 } else {23 low = mid + 1;24 }25 }26 return low;27}