So somehow a relative of mine got these restaurant vouchers that can be used to deduct 500 baht off of each receipt. It is possible to ask the restaurant to issue multiple receipts so that multiple vouchers can be used. The relative wishes to spend as little cash as possible (anything over the voucher value of 500 will have to be paid in cash)
More formally, the question is:
given a list of prices (being the prices of items to be ordered), what are the combinations of prices that would require the least amount of cash to be paid?
For example:
let prices = [425, 105, 185, 185, 185, 98, 145, 155, 125, 125, 135, 295, 295, 155, 125]
if I were to just sum the prices in the given order, stopping when sum is over 500:
[425 + 105], [185 + 185 + 185], [98 + 145 + 155 + 125], [125 + 135 + 295], [295 + 155 + 125]
Sums of each combination:
[530, 555, 523, 555, 575]
Amount over 500:
[30, 55, 23, 55, 75]
Total cash to pay: 238
What is the best combinations of prices that would require the least amount of cash?
So far I have attempted a brute-force approach by generating all permutations of the prices and calculating the required cash amount for each permutation in the same fashion as the above example (summing from left to right, stopping when >= 500). However, this approach resulted in heap out of memory error when there are more than 10 prices :(
Thanks in advance.
I got 238 as well, with backtracking.
The program below tries all available new combinations of the state:
It returns the recorded value achieved from that state if the state was previously seen, and avoids searching a branch known to lead to a result greater than or equal to the smallest recorded result so far. It recurses using a single object to store the state in memory and updates it as it backtracks.
There's also a tweak-able bound on how large a bin is allowed be (the line,
if (new_sum >= 1.2 * 500)
).