f=->(d,v){d<0?0:(a=v.select{|x|x[d]>0})[0]&&(b=v-a)[0]?2**d+[f[d-1,a],f[d-1,b]].min: f[d-1,v]} gets p f[30,gets.split.map(&:to_i)]