Problem:
Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10

Solution in Rust (1.15.1) (judge verdict: Accepted)

macro_rules! impl_magma {
  ($T:ty, $U:ty, | $op_lhs:pat, $op_rhs:pat | $op_ret:expr) => {
    impl $crate::math::algebra::Magma for $T {
      type Underlying = $U;

      fn op($op_lhs: &Self::Underlying, $op_rhs: &Self::Underlying) -> Self::Underlying {
        $op_ret
      }
    }
  };
}

macro_rules! impl_identity {
  ($T:ty, $id:expr) => {
    impl $crate::math::algebra::Identity for $T {
      fn identity() -> Self::Underlying {
        $id
      }
    }
  };
}

macro_rules! impl_invertible {
  ($t:ty, | $inv_x:pat | $inv_b:expr) => {
    impl $crate::math::algebra::Invertible for $t {
      fn invert($inv_x: &Self::Underlying) -> Self::Underlying {
        $inv_b
      }
    }
  };
}

macro_rules! impl_associative {
  ($T:ty) => {
    impl $crate::math::algebra::Associative for $T {}
  };
}

macro_rules! impl_commutative {
  ($T:ty) => {
    impl $crate::math::algebra::Commutative for $T {}
  };
}

fn solve<R: BufRead, W: Write>(_reader: R, _writer: &mut W) {
  let mut _scanner = Scanner::new(_reader);

  #[allow(unused_macros)]
  macro_rules! scan {
    ($T:ty) => {
      _scanner.next::<$T>().unwrap()
    };
    ($($T:ty),+) => {
      ($(scan!($T)),+)
    };
    ($T:ty; $n:expr $(; $m:expr)*) => {{
      let mut vec = Vec::with_capacity($n);
      for _ in 0..$n {
        vec.push(scan!($T $(; $m)*));
      }
      vec
    }};
  }

  #[allow(unused_macros)]
  macro_rules! scan_iter {
    ($T:ty; $n:expr) => {
      _scanner.take::<$T>($n).map(|x| x.unwrap())
    };
  }

  #[allow(unused_macros)]
  macro_rules! print {
    ($fmt:expr) => {
      write!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      write!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! println {
    ($fmt:expr) => {
      writeln!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      writeln!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprint {
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprintln {
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! dump {
    ($($x:expr),+) => {
      eprint!("[{}:{}] ", file!(), line!());
      eprintln!(concat!($(stringify!($x), " = {:?}; "),+), $($x),+);
    };
  }

  use data_structures::CumulativeSum;
  use math::algebra::AdditiveGroup;
  use std::iter::FromIterator;

  let (n, k) = scan!(usize, usize);
  let x = scan!(i64; n);

  if n == 1 {
    println!("{}", x[0].abs());
    return;
  } else if x[n - 1] < 0 {
    println!("{}", -x[n - k]);
    return;
  } else if x[0] > 0 {
    println!("{}", x[k - 1]);
    return;
  }

  let mut mid_i = None;
  let mut d = vec![];
  for i in 0..n - 1 {
    if x[i] <= 0 && 0 <= x[i + 1] {
      d.push(-x[i]);
      d.push(x[i + 1]);
      mid_i = Some((i, i + 1));
    } else {
      d.push(x[i + 1] - x[i]);
    }
  }
  let mid_i = mid_i.unwrap();
  dump!(mid_i, d);

  let d_cumsum = CumulativeSum::<AdditiveGroup<i64>>::from_iter(d.iter().cloned());

  let mut start = if mid_i.0 + 1 > k { mid_i.0 + 1 - k } else { 0 };
  let mut end = mid_i.0 + (k - mid_i.1);
  dump!(start, end);

  let mut min = i64::max_value();
  while start <= mid_i.0 && end < n {
    dump!(start..mid_i.0 + 1);
    let sum0 = d_cumsum.concat(start..mid_i.0 + 1);
    dump!(mid_i.1..end + 1);
    let sum1 = d_cumsum.concat(mid_i.1..end + 1);
    min = ::std::cmp::min(min, sum0 * 2 + sum1);
    min = ::std::cmp::min(min, sum0 + sum1 * 2);
    start += 1;
    end += 1;
  }

  println!("{}", min);
}

const STACK_SIZE_MEBIBYTES: Option<usize> = None;

fn main() {
  fn run_solver() {
    let stdin = stdin();
    let stdout = stdout();
    #[cfg(debug_assertions)]
    let mut writer = stdout.lock();
    #[cfg(not(debug_assertions))]
    let mut writer = ::std::io::BufWriter::new(stdout.lock());
    solve(stdin.lock(), &mut writer);
    writer.flush().unwrap();
  }
  if let Some(size) = STACK_SIZE_MEBIBYTES {
    let builder = thread::Builder::new().name("solve".to_string()).stack_size(size * 1024 * 1024);
    builder.spawn(run_solver).unwrap().join().unwrap();
  } else {
    run_solver();
  }
}

use io::Scanner;
use std::io::{stdin, stdout, BufRead, Write};
use std::thread;

pub mod math {
  pub mod algebra {
    pub use self::abelian_group::*;
    pub use self::additive_group::*;
    pub use self::associative::*;
    pub use self::commutative::*;
    pub use self::group::*;
    pub use self::identity::*;
    pub use self::invertible::*;
    pub use self::magma::*;
    pub use self::monoid::*;

    mod magma {
      pub trait Magma {
        type Underlying: Clone;

        fn op(lhs: &Self::Underlying, rhs: &Self::Underlying) -> Self::Underlying;

        fn op_assign(lhs: &mut Self::Underlying, rhs: &Self::Underlying) {
          *lhs = Self::op(lhs, rhs);
        }
      }
    }

    mod identity {
      use math::algebra::Magma;

      pub trait Identity: Magma {
        fn identity() -> Self::Underlying;

        fn prop(a: &Self::Underlying) -> bool
        where
          Self::Underlying: PartialEq,
        {
          Self::op(&Self::identity(), a) == *a && Self::op(a, &Self::identity()) == *a
        }
      }
    }

    mod invertible {
      use math::algebra::{Identity, Magma};

      pub trait Invertible: Magma + Identity {
        fn invert(&Self::Underlying) -> Self::Underlying;

        fn op_inverse(lhs: &Self::Underlying, rhs: &Self::Underlying) -> Self::Underlying {
          Self::op(lhs, &Self::invert(rhs))
        }

        fn op_inverse_assign(lhs: &mut Self::Underlying, rhs: &Self::Underlying) {
          *lhs = Self::op_inverse(lhs, rhs);
        }

        fn prop(a: &Self::Underlying) -> bool
        where
          Self::Underlying: Eq,
        {
          let identity = Self::identity();
          Self::op(a, &Self::invert(a)) == identity && Self::op(&Self::invert(a), a) == identity
        }
      }
    }

    mod associative {
      use math::algebra::Magma;

      pub trait Associative: Magma {
        fn prop(a: &Self::Underlying, b: &Self::Underlying, c: &Self::Underlying) -> bool
        where
          Self::Underlying: Eq,
        {
          Self::op(&Self::op(a, b), c) == Self::op(a, &Self::op(b, c))
        }
      }
    }

    mod commutative {
      use math::algebra::Magma;

      pub trait Commutative: Magma {
        fn prop(a: &Self::Underlying, b: &Self::Underlying) -> bool
        where
          Self::Underlying: Eq,
        {
          Self::op(a, b) == Self::op(b, a)
        }
      }
    }

    mod monoid {
      use math::algebra::{Associative, Identity, Magma};

      pub trait Monoid: Magma + Associative + Identity {}

      impl<T: Magma + Associative + Identity> Monoid for T {}

      macro_rules! impl_monoid {
        ($t:ty, $u:ty, | $op_l:pat, $op_r:pat | $op_b:expr, $id:expr) => {
          impl_magma! { $t, $u, | $op_l, $op_r | $op_b }
          impl_associative! { $t }
          impl_identity! { $t, $id }
        };
      }
    }

    mod group {
      use math::algebra::{Associative, Identity, Invertible, Magma};

      pub trait Group: Magma + Associative + Identity + Invertible {}

      impl<T: Magma + Associative + Identity + Invertible> Group for T {}

      macro_rules! impl_group {
        ($t:ty, $u:ty, | $op_l:pat, $op_r:pat | $op_b:expr, $id:expr, | $inv_x:pat | $inv_b:expr) => {
          impl_magma! { $t, $u, | $op_l, $op_r | $op_b }
          impl_associative! { $t }
          impl_identity! { $t, $id }
          impl_invertible! { $t, | $inv_x | $inv_b }
        };
      }
    }

    #[macro_use]
    mod abelian_group {
      use math::algebra::{Associative, Commutative, Identity, Invertible, Magma};

      pub trait AbelianGroup: Magma + Associative + Commutative + Identity + Invertible {}

      impl<T: Magma + Associative + Commutative + Identity + Invertible> AbelianGroup for T {}

      macro_rules! impl_abelian_group {
        ($t:ty, $u:ty, | $op_l:pat, $op_r:pat | $op_b:expr, $id:expr, | $inv_x:pat | $inv_b:expr) => {
          impl_magma! { $t, $u, | $op_l, $op_r | $op_b }
          impl_associative! { $t }
          impl_commutative! { $t }
          impl_identity! { $t, $id }
          impl_invertible! { $t, | $inv_x | $inv_b }
        };
      }
    }

    mod additive_group {
      #[allow(unused_imports)]
      use math::algebra::AbelianGroup;
      use std::marker::PhantomData;

      pub struct AdditiveGroup<T> {
        _marker: PhantomData<fn() -> T>,
      }

      macro_rules! impl_additive_group {
        ($($t:ty)+) => {$(
          impl_abelian_group! { AdditiveGroup<$t>, $t, |&lhs, &rhs| lhs + rhs, 0, |&x| -x }
        )+};
      }

      impl_additive_group! { i32 i64 isize }
    }
  }
}

pub mod misc {
  pub use self::byte_char::*;
  pub use self::byte_string::*;

  mod byte_char {
    use std::fmt::{Debug, Display, Error, Formatter};

    #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct ByteChar(pub u8);

    impl Debug for ByteChar {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "b\'{}\'", self.0 as char)
      }
    }

    impl Display for ByteChar {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "{}", self.0 as char)
      }
    }
  }

  mod byte_string {
    use misc::ByteChar;
    use std::fmt::{Debug, Display, Error, Formatter};

    #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct ByteString(pub Vec<ByteChar>);

    impl Debug for ByteString {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "b\"")?;
        for &c in &self.0 {
          write!(f, "{}", c.0 as char)?;
        }
        write!(f, "b\"")
      }
    }

    impl Display for ByteString {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        for &c in &self.0 {
          write!(f, "{}", c.0 as char)?;
        }
        Ok(())
      }
    }
  }
}

pub mod data_structures {
  pub use self::cumulative_sum::*;

  pub mod cumulative_sum {
    use math::algebra::{Group, Monoid};
    use std::iter::FromIterator;
    use std::ops::{Index, IndexMut, Range, RangeTo};

    pub struct CumulativeSum<M: Monoid> {
      vec: Vec<M::Underlying>,
    }

    impl<M: Monoid> FromIterator<M::Underlying> for CumulativeSum<M> {
      fn from_iter<I: IntoIterator<Item = M::Underlying>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let mut vec = Vec::with_capacity(1 + iter.size_hint().0);
        vec.push(M::identity());
        for x in iter {
          let sum = M::op(vec.last().unwrap(), &x);
          vec.push(sum);
        }
        vec.shrink_to_fit();
        CumulativeSum { vec: vec }
      }
    }

    impl<M: Monoid> CumulativeSum<M> {
      pub fn len(&self) -> usize {
        self.vec.len() - 1
      }

      pub fn prefix_concat(&self, range: RangeTo<usize>) -> &M::Underlying {
        debug_assert!(range.end <= self.len());
        &self.vec[range.end]
      }
    }

    impl<G: Group> CumulativeSum<G> {
      pub fn get(&self, index: usize) -> G::Underlying {
        debug_assert!(index < self.len());
        self.concat(index..index + 1)
      }

      pub fn concat(&self, range: Range<usize>) -> G::Underlying {
        assert!(range.start <= range.end);
        debug_assert!(range.end <= self.len());
        G::op(&G::invert(&self.vec[range.start]), &self.vec[range.end])
      }
    }

    impl<M: Monoid> Index<usize> for CumulativeSum<M> {
      type Output = M::Underlying;

      fn index(&self, index: usize) -> &M::Underlying {
        &self.vec[index + 1]
      }
    }

    impl<M: Monoid> Index<Range<usize>> for CumulativeSum<M> {
      type Output = [M::Underlying];

      fn index(&self, range: Range<usize>) -> &[M::Underlying] {
        &self.vec[range.start..range.end]
      }
    }

    impl<M: Monoid> IndexMut<Range<usize>> for CumulativeSum<M> {
      fn index_mut(&mut self, range: Range<usize>) -> &mut [M::Underlying] {
        &mut self.vec[range.start..range.end]
      }
    }
  }
}

pub mod io {
  pub use self::from_bytes::FromBytes;
  pub use self::scanner::Scanner;

  mod from_bytes {
    use misc::{ByteChar, ByteString};
    use std::str;
    use std::str::FromStr;

    #[derive(Debug)]
    pub struct FromBytesError;

    pub trait FromBytes: Sized {
      type Err;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err>;
    }

    impl FromBytes for ByteChar {
      type Err = FromBytesError;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        if bytes.len() == 1 {
          Ok(ByteChar(*unsafe { bytes.get_unchecked(0) }))
        } else {
          Err(FromBytesError)
        }
      }
    }

    impl FromBytes for ByteString {
      type Err = FromBytesError;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        Ok(ByteString(bytes.iter().cloned().map(ByteChar).collect()))
      }
    }

    impl<T: FromStr> FromBytes for T {
      type Err = T::Err;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        let s = if cfg!(debug_assertions) {
          str::from_utf8(bytes).unwrap()
        } else {
          unsafe { str::from_utf8_unchecked(bytes) }
        };
        T::from_str(s)
      }
    }
  }

  mod scanner {
    use io::FromBytes;
    use std::io::BufRead;
    use std::marker::PhantomData;

    pub struct Scanner<R> {
      reader: R,
      buffer: Vec<u8>,
      position: usize,
    }

    impl<R: BufRead> Scanner<R> {
      pub fn new(reader: R) -> Self {
        Scanner {
          reader: reader,
          buffer: vec![],
          position: 0,
        }
      }

      pub fn next<T: FromBytes>(&mut self) -> Result<T, T::Err> {
        FromBytes::from_bytes(self.next_bytes().unwrap_or(&[]))
      }

      pub fn take<T: FromBytes>(&mut self, n: usize) -> Take<R, T> {
        Take {
          scanner: self,
          n: n,
          _marker: PhantomData,
        }
      }

      pub fn next_bytes(&mut self) -> Option<&[u8]> {
        if self.buffer.is_empty() {
          self.read_line();
        }
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') => self.position += 1,
            Some(&b'\n') => self.read_line(),
            Some(_) => break,
            None => return None,
          }
        }
        let start = self.position;
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') | Some(&b'\n') | None => break,
            Some(_) => self.position += 1,
          }
        }
        Some(&self.buffer[start..self.position])
      }

      fn read_line(&mut self) {
        self.position = 0;
        self.buffer.clear();
        self.reader.read_until(b'\n', &mut self.buffer).unwrap();
      }
    }

    pub struct Take<'a, R: 'a, T> {
      scanner: &'a mut Scanner<R>,
      n: usize,
      _marker: PhantomData<fn() -> T>,
    }

    impl<'a, R: BufRead, T: FromBytes> Iterator for Take<'a, R, T> {
      type Item = Result<T, T::Err>;

      fn next(&mut self) -> Option<Self::Item> {
        if self.n > 0 {
          self.n -= 1;
          Some(self.scanner.next())
        } else {
          None
        }
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        (self.n, Some(self.n))
      }
    }

    impl<'a, R: BufRead, T: FromBytes> ExactSizeIterator for Take<'a, R, T> {}
  }
}