1509. Batch Production Limit

Medium3.5 points estimatedBinary SearchArray

A bakery makes identical batches. One batch consumes need[i] units of ingredient i. The bakery already holds stock[i] units of each ingredient and may buy any number of extra units of ingredient i at price[i] each, spending at most budget in total.

Return the largest number of whole batches x the bakery can produce, as a 64-bit integer. The cost of x batches is the sum over all ingredients of max(0, x * need[i] - stock[i]) * price[i], and it never decreases as x grows, so binary search x, abandoning a cost evaluation as soon as it passes budget. Expected time is O(n log X) with O(1) extra space.

Example 1

Input:
need = [2,1]stock = [5,0]price = [3,4]budget = 20
Output:
3
Explanation:

Three batches need 6 and 3 units, so 1 and 3 units must be bought for 1*3 + 3*4 = 15; four batches would cost 25, over the budget of 20.

Example 2

Input:
need = [1]stock = [0]price = [5]budget = 0
Output:
0
Explanation:

With no stock and no budget not even one batch can be made.

Example 3

Input:
need = [3,2]stock = [9,6]price = [7,7]budget = 0
Output:
3
Explanation:

Stock alone covers exactly three batches and nothing can be bought, so the answer is 3.

Constraints

1 ≤ n ≤ 105 (need, stock and price all have length n)

1 ≤ need[i], price[i] ≤ 100

0 ≤ stock[i] ≤ 109

0 ≤ budget ≤ 109

The answer is at most 2 * 109.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log X)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…