SPOJ COINS

346 Bytelandian gold coins
http://spoj.sphere.pl/problems/COINS

Summary
The main question in this problem is how to get optimal exchange value of coins. If you have coin with value n, you could exchange directly to get value n, or choose to exchange it first into 3 other coin values i.e n/2, n/3 and n/4.

Explanation
One of the simplest way to solve this problem is using DP + memoization. Sub problem relations clear from the summary is that for each value n you have to choose maximum between n and its exchange values i.e : calc(n) : max(n, calc(n/2)+calc(n/3)+calc(n/4) )

Implementation
Straightforward implementation in python (unlike Topcoder SPOJ accepts python), its basically the recurrence relation + base case 0 + memo. memo = {} def calc(n): global memo if n == 0 : return 0 if n in memo : return memo[n]

memo[n] = max(n, calc(n/2)+calc(n/3)+calc(n/4))

return memo[n] Although the constraint seems high : 0 <= n <= 1000 000 000, if you add a simple count variable in this implementation, it shows that for 1000000000 with memoization, this recurrence is only evaluated 754 times. (Somebody care to explain why ? ) We will be well within time limits.

Input
12 1000000000

Output
13 4243218150