oneby7

Binary Search Searching the answer

245. Find the Smallest Divisor Given a Threshold

Medium

You are given an array of positive integers nums and an integer threshold. Choose a positive whole number divisor. Divide every element of nums by it, round each result up to a whole number, and add the rounded results together.

Rounding up means that any fraction counts as a whole one. With divisor 4, the element 10 becomes 3, since 10 / 4 = 2.5, and the element 8 becomes 2.

Return the smallest divisor that keeps the sum at most threshold.

Example 1

Input: nums = [9, 4, 15, 7], threshold = 8

Output: 5

Explanation: With divisor 5 the elements become 2, 1, 3 and 2, and the sum is exactly 8. With divisor 4 they become 3, 1, 4 and 2, and the sum is 10, which is too much.

Example 2

Input: nums = [6, 2, 11, 3], threshold = 4

Output: 11

Explanation: The threshold equals the number of elements, so every element must become 1. That needs a divisor of at least 11, the largest element.

Example 3

Input: nums = [5, 1, 8, 2], threshold = 16

Output: 1

Explanation: Divisor 1 leaves every element as it is, and the sum is exactly 16. The divisor must be positive, so 1 is the smallest possible.

Check your understanding

Work out the answer for this input before you write any code.

nums = [7, 7, 7], threshold = 6

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • nums.length ≤ threshold ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.