Monday 8 December 2014

Bytelandian gold coins

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.

Recursion :: 
// n < 12 : We may get n or less than n when we do exchange.. so dont exchange when n<12
// 5 : 2+1+1 = 4, 6 : 3+2+1=6
//n >= 12 Similarly : We may get more than n or n when we do exchange.. so do exhange whenever n>=12
//Memoize intermediate results using a map.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package SPOJ;/**
 * Created by seesunda on 12/9/2014.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
// n < 12 : We may get n or less than n when we do exchange.. so dont exchange when n<12
// 5 : 2+1+1 = 4, 6 : 3+2+1=6

//n >= 12 Similarly : We may get more than n or n when we do exchange.. so do exhange whenever n>=12

//Memoize intermediate results using a map.
class coins {

    static HashMap<Long,Long> map = new HashMap<Long, Long>();

    public static void main(String[] args) throws IOException {
        BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        String s = "";
        while((s=inp.readLine())!=null) {
            long n = Long.parseLong(s);
            out.println(getMax(n));
        }
        out.flush();
    }

    public static long getMax(long n) {
        if(n < 12)
            return n;

        if(map.containsKey(n))
            return map.get(n);

        long chg = getMax(n/2) + getMax(n/3) + getMax(n/4);
        map.put(n,chg);

        return chg;
    }
}

No comments:

Post a Comment