n = gets.to_i arr = (1..n).to_a.map { |i| i.digits(2).count(1) } INF = 10000000 dp = [INF] * n dp[0] = 1 p arr arr.each_with_index do |num, i| # p dp, num, i if i + num <= n-1 dp[i+num] = [dp[i+num], dp[i] + 1].min end if i - num >= 0 dp[i-num] = [dp[i-num], dp[i] + 1].min end end if dp[n-1] == INF puts -1 return end puts dp[n-1]