Online store~20 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy
You work on a shop app that builds gift baskets. Each gift has a price in whole units. A customer holds a few vouchers, and each voucher halves the price of one gift, rounded down.
The customer asks: "How many different gifts can I buy within my budget?" Each gift is bought at most once, and a voucher works on one gift only. The shop can have 100,000 gifts.
Write most_gifts(prices, vouchers, budget).
prices[i] is the price of gift i.p makes it cost p // 2. Use at most vouchers vouchers, each on a different gift.budget.0 when no gift fits.Input: prices = [8, 3, 5, 2, 9], vouchers = 2, budget = 15
Output: 4Take the cheapest gifts first. For each count of gifts, put the vouchers on the dearest gifts of the set, and check the cost against the budget.
| Gifts | The cheapest gifts | Vouchers used | Cost | Within 15? |
|---|---|---|---|---|
| 1 | [2] | 1 | 1 | yes |
| 2 | [2, 3] | 2 | 2 | yes |
| 3 | [2, 3, 5] | 2 | 5 | yes |
| 4 | [2, 3, 5, 8] | 2 | 11 | yes |
| 5 | [2, 3, 5, 8, 9] | 2 | 18 | no |
The largest count that fits is 4.
Input: prices = [10, 20], vouchers = 0, budget = 5
Output: 0Both gifts cost more than the budget, and there are no vouchers.
Input: prices = [7], vouchers = 3, budget = 3
Output: 1A voucher makes the gift cost 3, which fits the budget exactly.
1 ≤ len(prices) ≤ 100,0001 ≤ prices[i] ≤ 1,000,0000 ≤ vouchers ≤ 100,0000 ≤ budget ≤ 1,000,000,000,000Trying every set of gifts means 2^100,000 sets, and trying every way to place the vouchers makes it worse. The clue is the size of the list. A sort costs about 1.7 million steps, and one pass over the counts costs 100,000 more. So the solution must choose without searching.