Payments app~15 min2s · 256 MBtarget O(n + k) time, O(k) spaceclassic twin: lc-561sorting · greedy
A payments app prints a reconciliation sheet from the day's receipts. The receipts are grouped into pairs, and each pair is credited with the smaller of its two amounts. The app has an even number of receipts, and each belongs to exactly one pair. Choose the pairs so that the total credit is as large as possible.
Write best_pair_credit(amounts).
amounts[i] is the amount of receipt i. The length of amounts is even.Input: amounts = [6, 2, 6, 5, 1, 2]
Output: 9Order the amounts from smallest to largest and pair neighbours. The smaller amount of each pair sits at an even place, counting from 0.
| Place | Amount | Even place? | Credit so far |
|---|---|---|---|
| 0 | 1 | yes: add 1 | 1 |
| 1 | 2 | no | 1 |
| 2 | 2 | yes: add 2 | 3 |
| 3 | 5 | no | 3 |
| 4 | 6 | yes: add 6 | 9 |
| 5 | 6 | no | 9 |
The even places hold 1, 2 and 6, so the best total credit is 9.
Input: amounts = [5, 5]
Output: 5There is only one pair, and its smaller amount is 5, so the answer is 5.
Input: amounts = [9, 1, 9, 1]
Output: 10Pairing 1 with 1 and 9 with 9 credits 1 and 9. The total is 10.
0 ≤ amounts.length ≤ 100,000, and the length is even (receipts)0 ≤ amounts[i] ≤ 10,000 (units)The amounts come from only 10,001 possible values. A counting array of that size is small, and counting is faster than comparing, because it costs n plus 10,001 steps.