Problem:
Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16

Solution in Ruby (2.3.3) (judge verdict: Runtime Error)

INF = 10**9

def coin(amount,kind,coins)
  coins = [0].concat(coins)
  dp = Array.new(kind+1).map{Array.new(amount+1, INF)}
  dp.each{|line| line[0]=1}

  for i in 1..kind
    for j in 1..amount
      if coins[i] > j
        dp[i][j] = dp[i-1][j]
      else
        count = (j-coins[i]/coins[i]) > 0 ? 1: 0
        dp[i][j] = [dp[i-1][j], dp[i][j-coins[i]] + count].min
      end
    end
  end
  dp
end

def pow_arr(n, max)
  arr = [n]
  cur = n
  while cur <= max
    cur = cur * n
    arr << cur
  end
  arr.delete(cur)
  arr
end

lines = $stdin.read
array = lines.split("\n")
N = array[0].to_i
six_pow = pow_arr(6, N)
nine_pow = pow_arr(9, N)

coins = [1]
coins = coins.concat(six_pow)
coins = coins.concat(nine_pow)
coins.uniq!.sort!

dp = coin(N, coins.length, coins)
puts dp[coins.length][N]