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| 
    hk = h.pop
    dp.push(h.map!.with_index { |x, k| (x - hk).abs + dp[k] }.min).shift
end

p dp.min-s[0]
