INF = 1000000 c = gets.to_i n = gets.to_i a = gets.split.map(&:to_i) dp = Array.new(n + 1) (n + 1).times{|i| dp[i] = Array.new(c + 1,INF) dp[i][0] = 0 } 1.upto(n){|i| 1.upto(a[i - 1] - 1){|j| dp[i][j] = dp[i - 1][j] } a[i - 1].upto(c){|j| dp[i][j] = [dp[i - 1][j], dp[i][j - a[i - 1]] + 1].min } } if dp[n][c] == INF p -1 else p dp[n][c] end