1476. Budget Picks Per Query

Easy1.5 points estimatedBinary SearchPrefix SumSortingArray

A market stall sells distinct items whose prices are listed in prices; each item can be bought at most once. Several shoppers arrive with spending limits listed in budgets, and each shopper wants to take home as many items as possible without spending more than the limit.

For every budgets[j], return the largest number of items that shopper can afford. Answers must be returned in the same order as budgets, and a limit of 0 buys nothing.

The best strategy is to buy the cheapest items first. Sort the prices, build running totals in 64-bit integers, and for each budget find by binary search the largest count whose running total stays within the limit. Aim for O((n + q) log n) time and O(n) space.

Example 1

Input:
prices = [5,2,8,3], budgets = [1,2,7,10,18,19]
Output:
[0,1,2,3,4,4]
Explanation:

Sorted prices 2, 3, 5, 8 have running totals 2, 5, 10, 18, so budgets 1, 2, 7, 10, 18, 19 afford 0, 1, 2, 3, 4, 4 items.

Example 2

Input:
prices = [4,4,4], budgets = [3,4,8,12]
Output:
[0,1,2,3]
Explanation:

Each item costs 4, so the budgets afford 0, 1, 2 and 3 items.

Constraints

1 ≤ prices.length, budgets.length ≤ 1000

1 ≤ prices[i] ≤ 106

0 ≤ budgets[j] ≤ 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 + q) log n)
Space
O(n)

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…