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 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 :

$$f( n ) = \max( n, f( \frac{n}{2} ) + f( \frac{n}{3} ) + f( \frac{n}{4} ) )$$

Implementation
Just implement the recurrence described above using memoization. Although the constraint seems high : 0 <= n <= 1000 000 000, it shows that for 1000000000 with memoization, this recurrence is only evaluated 754 times.

To get an approximate count on the recurrence, realize that at any state corresponds to some division of n by 2s and 3s. Any division by 4 is just a repeated division by 2. How many ways can we divide 1000 000 000 by 2? Approximately $$log_2(1000 000 000)$$. And how many times can we divide 1000 000 000 by 3? Approximately $$log_3(1000 000 000)$$. Since the division operations are independent, have have $$log_2(1000 000 000) * log_3(1000 000 000) = 552$$.

We will be well within time limits.

Use the class map of the STL in C++. See.

Input
12 1000000000

Output
13 4243218150

Solutions
F#: http://adilakhter.wordpress.com/2013/02/26/spoj-346-bytelandian-gold-coins-coins/