Write for the voucher after buying a product priced . The final value can never exceed the largest price .
If is odd, reserve a maximum-priced product for last. Pair the other products and buy the larger price before the smaller price in each pair. Starting with voucher zero, each pair ends with voucher zero. The last purchase gives , attaining the upper bound.
For even , sort the prices as and define
The answer is .
To prove the bound , fix any purchase order. Changing one price by changes the final voucher by at most : changing that purchase changes its output by at most this amount, and each later function cannot magnify the difference between two inputs. Choose . If all prices were , the even-length sequence would end at zero. Changing them back one at a time shows that the final voucher is at most
To attain the bound, buy , followed by the pairs
and buy last. Before each pair the voucher is at most . For the pair's larger and smaller prices , its effect is
These subtractions leave the voucher before the last purchase equal to
The final purchase therefore gives . For , the list of middle pairs is empty and the same argument applies.
Sorting takes time and memory. Use signed 64-bit integers for the sums, even though the answer is at most . Sorting the purchase order increasingly is not generally optimal; sorting is used to compute the formula.