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

#!/usr/bin/env ruby

# Generated by AtcoderGreedy on 2018-06-10
# ABC099 C

# my lib

module Enumerable
  # work just like String#split,
  # except this method does not use regex match
  # but check whether yield succeeds or not.
  def split
    current = nil
    ret = []
    each do |elem|
      if yield elem
        if current
          ret << current
          current = nil
        end
      elsif current
        current << elem
      else
        current = [elem]
      end
    end
    ret << current if current
    ret
  end
end

class Array
  # truncate tail, opposite of drop
  def clip(amount = 1)
    if amount < 0
      raise ArgumentError, "amount == #{amount}, cannot be negative!"
    end
    take_amount = size - amount
    take_amount < 0 ? [] : take(take_amount)
  end
end

def n_choose_k(n, k)
  return 0 unless (0..n).cover? k
  result = 1
  1.upto(k) do |d|
    result *= n
    result /= d
    n -= 1
  end
  result
end

# end of lib

# Your code here

require 'set'

MAX = 100_000

arr = { 0 => 0 }
edges = [0]

def withdraws(base)
  ret = [base]
  cand = ret.last * base
  while cand <= MAX
    ret << cand
    cand = ret.last * base
  end
  ret
end

withds = [1] + withdraws(6) + withdraws(9)
withds = withds.sort

WITHDRAWS = withds

N = gets.to_i

edges = [0]
n = 0

until edges.empty?
  n += 1
  next_edges = []
  edges.each do |e|
    WITHDRAWS.each do |w|
      next_ind = e + w
      break if next_ind > MAX
      unless arr[next_ind]
        arr[next_ind] = n
        next_edges << next_ind
      end
    end
  end
  edges = next_edges
end

puts arr[N]