Online store~15 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
An online store sorts the prices in one category from the cheapest to the most expensive. A shopper types a budget, and the app suggests the price that is closest to it, even if it is a little above the budget.
When two prices are the same distance from the budget, the app suggests the cheaper one.
Write closest_prices(prices, budgets).
prices is the sorted list of prices and has at least one entry.|price - budget|.Input: prices = [10, 20, 20, 35, 50], budgets = [22, 15, 60, 5, 35]
Output: [20, 10, 50, 10, 35]Take the budget 15. The window [lo, hi) starts as [0, 5) and finds the first price that is not below 15.
| Step | lo | hi | mid | prices[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 20 | not below 15, so hi = 2 |
| 2 | 0 | 2 | 1 | 20 | not below 15, so hi = 1 |
| 3 | 0 | 1 | 0 | 10 | 10 < 15, so lo = 1 |
| end | 1 | 1 | the neighbours are prices[0] = 10 and prices[1] = 20 |
Both are 5 away from 15, so the cheaper one wins: 10.
The budget 22 has the neighbours 20 and 35, so it gets 20. The budget 60 is above every price and gets 50. The budget 5 is below every price and gets 10. The budget 35 is a price, so it gets 35.
Input: prices = [40], budgets = [0, 40, 99]
Output: [40, 40, 40]With one price, every budget gets that price.
Input: prices = [7, 7, 7], budgets = [6, 7, 8]
Output: [7, 7, 7]When every price is equal, every answer is that price.
1 ≤ prices.length ≤ 100,000, and prices is sorted from smallest to largest, repeats allowed0 ≤ budgets.length ≤ 100,0000 ≤ prices[i], budgets[j] ≤ 10,000,000 (prices and budgets in minor units)Comparing every price with every budget costs about n × q steps, which is 10^10 when both are 100,000. The prices are sorted. A binary search finds the place where a budget would fit, and the nearest price is a neighbour of that place.