a,b=0,1 gets.chop.chars{|c|x=c.ord-48 # y=x/5;a,b=[a+y,b+2-y].min,[a+1+y,b+1-y].min # y=x%5;a,b=[a+y,b+5-y].min,[a+1+y,b+4-y].min f=[0,1,2,3,2,1,2,3,4,3,2] a,b=[a+f[x],b+f[10-x]].min,[a+f[1+x],b+f[9-x]].min } p [a,b+1].min