Online store~20 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-2824opposite-ends · two-pointers · sorting
An online store is adding a gift feature. A shopper enters a gift budget, and the shop suggests two different products whose prices together stay within it.
Before launch, the merchandising team wants to know how rich each gift catalogue is for a given budget. They ask for one number: how many pairs of products fit. Prices are integers in minor units, and the catalogue is stored in no particular order. Two products can have the same price, and they still count as different products.
Write count_gift_pairs(prices, budget).
prices[i] is the price of product i in minor units. The list is not sorted.budget is the gift budget in minor units.i < j with prices[i] + prices[j] ≤ budget.budget fits.0.Input: prices = [45, 30, 80, 20, 55, 10], budget = 75
Output: 8Sorted, the prices are [10, 20, 30, 45, 55, 80]. The trace works on that sorted copy.
| left | right | ordered[left] | ordered[right] | Total | Within 75? | Pairs added | count |
|---|---|---|---|---|---|---|---|
| 0 | 5 | 10 | 80 | 90 | no | 0 | 0 |
| 0 | 4 | 10 | 55 | 65 | yes | 4 | 4 |
| 1 | 4 | 20 | 55 | 75 | yes | 3 | 7 |
| 2 | 4 | 30 | 55 | 85 | no | 0 | 7 |
| 2 | 3 | 30 | 45 | 75 | yes | 1 | 8 |
When 10 + 55 fits, 10 also fits with 20, 30 and 45, which are cheaper than 55. That is 4 pairs counted in one step.
Input: prices = [30, 30, 30, 50], budget = 60
Output: 3The three products at 30 make 3 pairs, each exactly on the budget. Every pair with the 50 costs 80.
Input: prices = [120], budget = 500
Output: 0One product cannot make a pair.
1 ≤ prices.length ≤ 10^51 ≤ prices[i] ≤ 10^71 ≤ budget ≤ 2 × 10^7Checking every pair costs n × (n − 1) / 2 checks: about 5 × 10^9 at n = 10^5. That is far over the budget of about 10^8 simple operations a second. Sorting costs about n log n, roughly 1.7 × 10^6 steps, so sorting first and then making one pass fits easily.
Read the answer's size too. When every pair fits, the count is 4,999,950,000, which does not fit in a 32-bit integer. Use long in Java and long long in C++.