Online store~20 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy · sorting
An online shop runs a bundle offer. When a customer buys a group of items together, the cheapest item of the group is free. A group has a fixed number of items.
At checkout, the shop groups the items in the cart in the way that is best for the customer. Items that do not fill a group are paid in full. The shop shows the total to pay.
Write cart_total(prices, group).
prices[i] is the price in units of item i in the cart.group items. In each bundle, the cheapest item is free. If several items share the lowest price, only one of them is free.long.Input: prices = [30, 90, 20, 60, 50, 10, 40], group = 3
Output: 230The trace sorts the prices from the most expensive, and makes a bundle of every 3 items in that order.
| Position, most expensive first | Price | Paid or free |
|---|---|---|
| 0 | 90 | paid |
| 1 | 60 | paid |
| 2 | 50 | free |
| 3 | 40 | paid |
| 4 | 30 | paid |
| 5 | 20 | free |
| 6 | 10 | paid |
The cart costs 300 units before the offer. The free items are the third item, priced 50, and the sixth, priced 20. That saves 70 units, so the customer pays 230. The cheapest item, 10, is left over and pays in full.
Input: prices = [5, 5], group = 3
Output: 10The cart has only 2 items, and a bundle needs 3. No bundle can be made, so the customer pays 10.
Input: prices = [8, 3, 5, 5], group = 2
Output: 13The best bundles are 8 with 5, and 5 with 3. The free items cost 5 and 3. The total is 21 - 8 = 13.
1 ≤ prices.length ≤ 100,000; 1 ≤ prices[i] ≤ 10,000,000 (units)2 ≤ group ≤ 100,000Trying every way to group the items is far too slow: the number of groupings grows faster than any power of n. A rule that picks the groups by sorting costs O(n log n). The total can reach 10^5 × 10^7 = 10^12, which needs a 64-bit integer.