# AtCoder Beginner Contest 107

URL: https://atcoder.jp/contests/abc107 (opens new window)

# C

n,k = gets.chomp.split(" ").map(&:to_i)
x_arr = gets.chomp.split(" ").map(&:to_i)

# -10 ** 8 から 10 ** 8 の間を移動するのが最長
min = (10 ** 8) * 3
(0..(n - k)).each do |i|
  left = x_arr[i]
  right = x_arr[k - 1 + i]
  if left < 0 && right < 0
    # 0 -> left とたどる
    d = left.abs
  elsif left > 0 && right > 0
    # 0 -> right とたどる
    d = right.abs
  elsif left.abs > right.abs
    # 0 -> right -> 0 -> left とたどる
    d = right.abs * 2 + left.abs
  else
    # 0 -> left -> 0 -> right とたどる
    d = left.abs * 2 + right.abs
  end
  min = d if d < min
end

puts min
Last Updated: 2020/08/29 17:41