$h={} def f a,b $h[a+b.sort]||=(if a[0] (0..b.size-1).map{|i| c=b.dup n,_=c[i] if n>=a[0] c[i]=[n-a[0],true] f(a[1..-1],c) else nil end }.compact.min else b.count{|i,j|j} end) end gets a=gets.split.map(&:to_i) gets b=gets.split.map{|c|[c.to_i,false]} p f(a,b)||-1