K = gets[/ .*/].to_i
s = gets.split.map(&:to_i)
dp = [s[0]] * K
s.push(*([s[-1]] * K)).unshift(*([s[0]] * K)).each_cons(K+1) do |h| 
    dp.push([h.pop].product(h).zip(dp).map { |(x, y), z| (x - y).abs + z }.min).shift
end

p dp.min-s[0]
