Skip to content

Instantly share code, notes, and snippets.

@sarahzrf
Created December 8, 2021 00:08
Show Gist options
  • Save sarahzrf/01c967a072bb0697eb6c97c6fc50b8b0 to your computer and use it in GitHub Desktop.
Save sarahzrf/01c967a072bb0697eb6c97c6fc50b8b0 to your computer and use it in GitHub Desktop.
class Integer
def sumtorial
(0..self).sum
end
end
def cost(counts, x0)
counts.sum {|x, n| (x0 - x).abs.sumtorial * n}
end
count_by_pos = Hash.new(0)
gets.chomp.split(',').map(&:to_i).each do |x|
count_by_pos[x] += 1
end
rg = count_by_pos.keys.min..count_by_pos.keys.max
optimal = rg.map {|x| cost(count_by_pos, x)}.min
print optimal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment