Bytelandian gold coins

Nishant Arora 17/Mar/2013
Facebook
Twitter
LinkedIn
Reddit

This is one of the most amazing dynamic programming problems I solved till date. The problem sounds simple and seems to be easily doable. but here is the catch, it ain't that easy. For those interested in the problem statement, here you go, it's available on CodeChef, SPOJ and HackerEarth.

In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit).

You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it?

Input The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin.

Output For each test case output a single line, containing the maximum amount of American dollars you can make.

Explanation You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. It is better just to change the 2 coin directly into $2.

My initial approach was too subtle and narrow and I never thought that the coins could be exchanged multiple times. So the solution is simple as the following pseudo code:

1. exchange the coin from bank as n/2+n/3+n/4 and select the max out of the two. i.e max(n, (n/2+n/3+n/4))
2. maintain these conversion in a key=>value array so that we need not calculate these again and again
3. for each n/2, n/3, n/4 repeat steps 1,2 and 3

So here is the solution in Python:

#maintaining a dictionary
conv = {0:0}

def exch(num):
    if num in conv:
        return conv[num]
    else:
        conv[num] = max(num, exch(num/4)+exch(num/3)+exch(num/2))
        return conv[num]
while True:
    try:
        print exch(int(raw_input()))
    except:
        break

here is the working code. It won't work in PHP as it will most probably run out of memory.

Cheers!... happy coding!...