class Yukicoder def initialize remain = gets.to_i n = gets.to_i candy = [] n.times do candy << gets.to_i end answer = 0 if candy.size == 1 puts "0" return end a = 0 b = candy.max answer = candy.inject(:+) #0.upto(b) do |j| # puts "num = #{candy.inject(0){|sum,i| sum += (j < i)? i-j : j-i}}" #end while a < b-2 c = a + (b-a)/3 d = [a + 2 * ((b-a)/3), b].min v1 = candy.inject(0){|sum,i| sum += (c < i)? i-c : c-i} v2 = candy.inject(0){|sum,i| sum += (d < i)? i-d : d-i} if v1 < v2 b = d else a = c+1 end end min_val = Float::INFINITY a.upto(b) do |j| min_val = [min_val, candy.inject(0){|sum,i| sum += (j < i)? i-j : j-i}].min end puts min_val end end Yukicoder.new