macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    ($arg:expr) => (println!("{:?}",$arg));
}

#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

use std::collections::HashMap;
use std::cmp::Ordering;

fn main() {
    input!{
        n:i32,
        restaurant : [(String , i32);n],
    }

   let mut result  = restaurant.into_iter().enumerate().map(|(i,(s,p))| (i,s,p)).collect::<Vec<_>>();
   //.map(|i,(s,u)| (i,s,u)).collect();
   result.sort_by(|r,l| {
       if r.1 != l.1 {return r.1.cmp(&l.1)}
       else{
           match r.2.cmp(&l.2) {
               Ordering::Less => {return Ordering::Greater}
               _ => {return Ordering::Less}
           }
       }
   });

    let ret = result.iter().map(|(index,a,b)| (index+1).to_string()).collect::<Vec<_>>();

   println!("{}",ret.connect("\n"));

}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    ($arg:expr) => (println!("{:?}",$arg));
}

#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

use std::collections::HashMap;
use std::cmp::Ordering;

fn main() {
    input!{
        n:i32,
        restaurant : [(String , i32);n],
    }

   let mut result  = restaurant.into_iter().enumerate().map(|(i,(s,p))| (i,s,p)).collect::<Vec<_>>();
   //.map(|i,(s,u)| (i,s,u)).collect();
   result.sort_by(|r,l| {
       if r.1 != l.1 {return r.1.cmp(&l.1)}
       else{
           match r.2.cmp(&l.2) {
               Ordering::Less => {return Ordering::Greater}
               _ => {return Ordering::Less}
           }
       }
   });

    let ret = result.iter().map(|(index,_,_)| (index+1).to_string()).collect::<Vec<_>>();

   println!("{}",ret.connect("\n"));

}


let arr: [(Int, String, Int)] = (1...Int(readLine()!)!).map{
  let input = readLine()!.characters.split(" ").map{String($0)}
  return ($0, input[0], Int(input[1])!)
}
for element in arr.sort({$0.1==$1.1 ? $0.2>$1.2 : $0.1<$1.1}) {
  print(element.0)
}


var arr = [(Int, String, Int)]()
for i in 1...Int(readLine()!)! {
  let input = readLine()!.characters.split(" ").map{String($0)}
  arr += [(i, input[0], Int(input[1])!)]
}
for element in arr.sort({if $0.1==$1.1{return $0.2>$1.2};return $0.1<$1.1}) {
  print(element.0)
}


struct Restaurant {
  let index: Int
  let city: String
  let point: Int
}

var table: [String: [Restaurant]] = [:]

let N = Int(readLine()!)!

for i in 1...N {
  let inp = readLine()!.split(separator: " ").map { String($0) }
  table[inp[0], default: []].append(Restaurant(index: i, city: inp[0], point: Int(inp[1])!))
}
for key in table.keys.sorted() {
  for r in table[key]!.sorted { $0.point > $1.point } {
    print(r.index)
  }
}


func sReadLine() -> [String] {
    return readLine()!.characters.split(" ").map{String($0)}
}
func sReadInt() -> [Int] {
    let strs = sReadLine()
    return strs.map{Int($0)!}
}
func readInt() -> Int {
    return Int(readLine()!)!
}
/************** main *****************/
var sparr: [(String, Int, Int)] = (1...n).map { i in
    let sp = sReadLine()
    return (sp[0], Int(sp[1])!, i)
}
for ssp in sparr.sort({$0.0 == $1.0 ? $0.1 > $1.1 : $0.0 < $1.0}) {
    print(ssp.2)
}


func sReadLine() -> [String] {
    return readLine()!.characters.split(" ").map{String($0)}
}
func sReadInt() -> [Int] {
    let strs = sReadLine()
    return strs.map{Int($0)!}
}
func readInt() -> Int {
    return Int(readLine()!)!
}
/************** main *****************/
let n = readInt()
var sparr: [(String, Int, String)] = (1...n).map { i in
    let sp = sReadLine()
    return (sp[0], Int(sp[1])!, sp[0] + " " + sp[1])
}
for ssp in sparr.sort({$0.0 == $1.0 ? $0.1 > $1.1 : $0.0 < $1.0}) {
    print(ssp.2)
}


function Main(input) {
	const data = input.trim().split("\n");
  	const n = Number(data[0]);
  	const sps = data.slice(1).map(d => d.split(" "));
  	const sortedSps = sps.slice();
  	sortedSps.sort((a, b) => {
    	if (a[0] < b[0]) {
          return -1;
        } else if (b[0] < a[0]) {
          return 1;
        } else {
          if (Number(a[1]) < Number(b[1])) {
            return 1;
          } else {
            return -1;
          }
        }
    });
  	const result = [];
  	for (let i = 0; i < sps.length; i++) {
      const index = sps.findIndex(sp => sp[0] === sortedSps[i][0] && sp[1] === sortedSps[i][1]);
      result.push(index + 1);
    }
    console.log(result.join("\n").trim());

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'
const main = (input: string) => {
    const std: string[] = input.split('\n')
    const n: number = ~~std.shift()
    let l: string[] = std.map((v,i) => {
        const [key, val] = v.split(' ')
        // 文字列ソートなので3桁の数値になるようにしとく
        return `${key}${999 - Number(val)},${++i}`
    }).sort()
    const r = l.forEach(v => console.log(v.split(',')[1]))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim())


export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = Number(tmp[0]);
    const list: [number, string, number][] = [];
    for (let i = 1; i <= n; ++i) {
      const t: string[] = tmp[i].split(" ");
      list.push([i, t[0], Number(t[1])]);
    }
    list.sort(([n1, s1, p1], [n2, s2, p2]) => s1 < s2 ? -1 :
                                              s1 > s2 ? 1 :
                                              p2 - p1);
    return `${list.map(([i, s, p]) => i).join("\n")}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  lines.forEach(line => {
    console.log(line.id.toString());
  });
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  lines.forEach(line => {
    console.log(line.id);
  });
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


function Main(input) {
  const lines = input.split("\n").slice(1).map((line, i) => {
    const [S, P] = line.split(' ');
    return { name: S, score: P, id: i + 1 };
  });
  lines.sort((a, b) => {
    if (a.name > b.name) {
      return 1;
    }
    else if (a.name < b.name) {
      return -1;
    }
    else {
      return b.score - a.score;
    }
  });
  const ans = lines.map(line => line.id).join('\n');
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


# ABC107C - Candles (ARC101C)
def main():
    N, K, *X = map(int, open(0).read().split())
    ans = float("inf")
    for l, r in zip(X, X[K - 1 :]):
        x = r - l + min(abs(l), abs(r))
        ans = x if x < ans else ans
    print(ans)

if __name__ == "__main__":
    main()


import sys
input = sys.stdin.readline

def fullsearch(x, k):
    for l, r in zip(x, x[k-1:]):
        distance = abs(r - l)
        yield distance + abs(r)
        yield distance + abs(l)

def main():
    _, K = map(int, input().split())
    X = list(map(int, input().split()))

    print(min(fullsearch(X, K)))

main()


import sys
input = sys.stdin.readline

X = []
K = 0
def fullsearch():
    for l, r in zip(X, X[K-1:]):
        distance = abs(r - l)
        yield distance + abs(r)
        yield distance + abs(l)

def main():
    global X, K
    _, K = map(int, input().split())
    X = list(map(int, input().split()))

    print(min(fullsearch()))

main()


url = "https://atcoder.jp//contests/abc107/tasks/arc101_a"

def main():
    n, k = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    # if xs[0] < 0 <= xs[-1]:
    #     pass
    # else:
    #     print(abs(xs[k*-1]))
    #     exit()

    ans = 100000000
    se = [0, k-1]
    while se[1] < n:
        if xs[se[0]] < 0 <= xs[se[1]]:
            tmp = min(abs(xs[se[0]]), xs[se[1]]) * 2 + max(abs(xs[se[0]]), xs[se[1]])
            ans = min(ans, tmp)
        elif xs[se[0]] < 0:
            ans = min(ans, abs(xs[se[0]]))
        elif xs[se[1]] > 0:
            ans = min(ans, xs[se[1]])
        se = [v + 1 for v in se]
    print(ans)

if __name__ == '__main__':
    main()


url = "https://atcoder.jp//contests/abc107/tasks/arc101_a"

def main():
    n, k = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    if xs[0] < 0 <= xs[-1]:
        pass
    else:
        print(abs(xs[k*-1]))
        exit()

    ans = 100000000
    se = [0, k-1]
    while se[1] < n:
        if xs[se[0]] < 0 <= xs[se[1]]:
            tmp = min(abs(xs[se[0]]), xs[se[1]]) * 2 + max(abs(xs[se[0]]), xs[se[1]])
            ans = min(ans, tmp)
        elif xs[se[0]] < 0:
            ans = min(ans, abs(xs[se[0]]))
        elif xs[se[1]] > 0:
            ans = min(ans, xs[se[1]])
        se = [v + 1 for v in se]
    print(ans)

if __name__ == '__main__':
    main()


n,k = map(int,input().split())
x = list(map(int,input().split()))
ans = x[-1]-x[0]
for i in range(n-k+1):
    ans = min(ans,x[i+k-1]-x[i])
print(ans)


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author gaidash
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        CCandles solver = new CCandles();
        solver.solve(1, in, out);
        out.close();
    }

    static class CCandles {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int nLight = in.nextInt();
            int[] a = in.nextIntArray(n);

            long ret = Long.MAX_VALUE;
            for (int i = 0; i < n; i++) {
                int toHere = Math.abs(a[i]);
                if (i + nLight - 1 < n) {
                    ret = Math.min(ret, toHere + Math.abs(a[i] - a[i + nLight - 1]));
                }
                if (i + 1 >= nLight) {
                    ret = Math.min(ret, toHere + Math.abs(a[i] - a[i - nLight + 1]));
                }
            }

            out.println(ret);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] nextIntArray(int n) {
            int[] array = new int[n];
            for (int i = 0; i < n; ++i) array[i] = nextInt();
            return array;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(long i) {
            writer.println(i);
        }

    }
}


/**
 * Created at 01:10 on 2019-06-27
 */

import java.io.*;
import java.util.*;

public class Main implements Runnable {

  static FastScanner sc = new FastScanner();

  static int[] dx = {0, 1, 0, -1};
  static int[] dy = {-1, 0, 1, 0};

  static long MOD = (long) (1e9 + 7);

  public static void main(String[] args) {

    //新しくスレッドを立てているので、これがないとREがWAと表示されてしまう
    //Thread.setDefaultUncaughtExceptionHandler((t,e)->System.exit(1));

    //スタックサイズを128MBに設定する(再帰呼び出し時のStackOverflowを防ぐ)
    //new Thread(null, new ABC107_C(), "", 128 * 1024 * 1024).start();

    new Main().run();

  }

  public void run() {

    int N = sc.nextInt();
    int K = sc.nextInt();

    long[] x = sc.nextLongArray(N, false);

    long ans = Long.MAX_VALUE;
    for (int i=K-1; i<N; i++) {
      if (i-K+1<0) continue;

      ans = Math.min(ans, x[i]-x[i-K+1] + Math.min(Math.abs(x[i-K+1]), Math.abs(x[i])));
    }
    System.out.println(ans);

  }

  public static class Mathf {

    public static int max(int[] a) {
      int M = a[0];
      for (int i = 1; i < a.length; i++) {
        M = Math.max(M, a[i]);
      }
      return M;
    }

    public static int min(int[] a) {
      int m = a[0];
      for (int i = 1; i < a.length; i++) {
        m = Math.min(m, a[i]);
      }
      return m;
    }

    public static long max(long[] a) {
      long M = a[0];
      for (int i = 1; i < a.length; i++) {
        M = Math.max(M, a[i]);
      }
      return M;
    }

    public static long min(long[] a) {
      long m = a[0];
      for (int i = 1; i < a.length; i++) {
        m = Math.min(m, a[i]);
      }
      return m;
    }

  }

  /*
    add()でインデックスを指定しない場合指定されたソート順に違わない位置に追加する
    (ただしソートされていることが前提となる)
    Comparatorが0を返したとき、それらの順序は保証しない
    (TreeSet, TreeMapと違い削除はしない)
   */
  static class TreeList<E> extends ArrayList<E> {

    Comparator<? super E> comparator;

    TreeList(Comparator<? super E> c) {
      super();
      comparator = c;
    }

    /*
      ソート済みのリストに要素を追加する
     */
    public boolean add(E e) {
      int lowIndex = 0;
      int highIndex = size() - 1;
      int index = 0;

      if (size() == 0) {
        super.add(e);
        return true;
      }

      if (comparator.compare(e, get(0)) < 0) {
        index = 0;
      } else if (comparator.compare(e, get(highIndex)) > 0) {
        index = highIndex + 1;
      } else {
        while (lowIndex <= highIndex) {

          if (highIndex == lowIndex + 1 || highIndex == lowIndex) {
            index = highIndex;
            break;
          }

          int midIndex = (lowIndex + highIndex) / 2;
          ;

          if (comparator.compare(e, get(midIndex)) > 0) {
            lowIndex = midIndex;
          } else {
            highIndex = midIndex;
          }

        }
      }

      super.add(index, e);
      return true;
    }

  }

  static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
      if (ptr < buflen) {
        return true;
      } else {
        ptr = 0;
        try {
          buflen = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (buflen <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    public boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    public long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int N, boolean oneBased) {
      if (oneBased) {
        int[] array = new int[N + 1];
        for (int i = 1; i <= N; i++) {
          array[i] = sc.nextInt();
        }
        return array;
      } else {
        int[] array = new int[N];
        for (int i = 0; i < N; i++) {
          array[i] = sc.nextInt();
        }
        return array;
      }
    }

    public long[] nextLongArray(int N, boolean oneBased) {
      if (oneBased) {
        long[] array = new long[N + 1];
        for (int i = 1; i <= N; i++) {
          array[i] = sc.nextLong();
        }
        return array;
      } else {
        long[] array = new long[N];
        for (int i = 0; i < N; i++) {
          array[i] = sc.nextLong();
        }
        return array;
      }
    }
  }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Closeable;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author HBonsai
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CCandles solver = new CCandles();
        solver.solve(1, in, out);
        out.close();
    }

    static class CCandles {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int N = in.nextInt();
            int K = in.nextInt();
            long[] xs = in.nextLongArray(N);
            long ans = Long.MAX_VALUE;
            for (int l = 0; l + K - 1 < N; l++) {
                int r = l + K - 1;
                long cand1 = Math.abs(xs[l]) + xs[r] - xs[l];
                long cand2 = Math.abs(xs[r]) + xs[r] - xs[l];
                ans = Math.min(ans, Math.min(cand1, cand2));
            }
            out.println(ans);
        }

    }

    static class FastScanner implements Closeable {
        private final InputStream in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;

        public FastScanner(InputStream in) {
            this.in = in;
        }

        private boolean hasNextByte() {
            if (ptr < buflen) {
                return true;
            } else {
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (buflen <= 0) {
                    return false;
                }
            }
            return true;
        }

        private int readByte() {
            if (hasNextByte()) return buffer[ptr++];
            else return -1;
        }

        private static boolean isPrintableChar(int c) {
            return 33 <= c && c <= 126;
        }

        public boolean hasNext() {
            while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
            return hasNextByte();
        }

        public long nextLong() {
            if (!hasNext()) throw new NoSuchElementException();
            long n = 0;
            boolean minus = false;
            int b = readByte();
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            if (b < '0' || '9' < b) {
                throw new NumberFormatException();
            }
            while (true) {
                if ('0' <= b && b <= '9') {
                    n *= 10;
                    n += b - '0';
                } else if (b == -1 || !isPrintableChar(b)) {
                    return minus ? -n : n;
                } else {
                    throw new NumberFormatException();
                }
                b = readByte();
            }
        }

        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
            return (int) nl;
        }

        public long[] nextLongArray(int n) {
            long[] res = new long[n];
            for (int i = 0; i < n; i++) {
                res[i] = nextLong();
            }
            return res;
        }

        public void close() {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public final class Main {

    public static void main(String[] args) {
        final FastScanner fs = new FastScanner();
        final int n = fs.nextInt();
        final int k = fs.nextInt();
        final int[] arr = fs.nextIntArray(n);
        long res = (long) 1e18;
        for (int i = 0; i < n - k; i++) {
            final long L = arr[i];
            final long R = arr[k + i - 1];
            final long curr = R - L + Math.min(Math.abs(L), Math.abs(R));
            res = Math.min(res, curr);
        }
        System.out.println(res);
    }

    static final class Util {
        public static void shuffleSort(int[] x) {
            shuffle(x);
            Arrays.sort(x);
        }

        public static void shuffleSort(long[] x) {
            shuffle(x);
            Arrays.sort(x);
        }

        public static void shuffle(int[] x) {
            final Random r = new Random();

            for (int i = 0; i <= x.length - 2; i++) {
                final int j = i + r.nextInt(x.length - i);
                swap(x, i, j);
            }
        }

        public static void shuffle(long[] x) {
            final Random r = new Random();

            for (int i = 0; i <= x.length - 2; i++) {
                final int j = i + r.nextInt(x.length - i);
                swap(x, i, j);
            }
        }

        public static void swap(int[] x, int i, int j) {
            final int t = x[i];
            x[i] = x[j];
            x[j] = t;
        }

        public static void swap(long[] x, int i, int j) {
            final long t = x[i];
            x[i] = x[j];
            x[j] = t;
        }

        private Util() {}
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        private String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    //noinspection CallToPrintStackTrace
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int[] nextIntArray(int n) {
            final int[] a = new int[n];
            for (int i = 0; i < n; i++) { a[i] = nextInt(); }
            return a;
        }

        long[] nextLongArray(int n) {
            final long[] a = new long[n];
            for (int i = 0; i < n; i++) { a[i] = nextLong(); }
            return a;
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public final class Main {

    public static void main(String[] args) {
        final FastScanner fs = new FastScanner();
        final int n = fs.nextInt();
        final int k = fs.nextInt();
        final int[] arr = fs.nextIntArray(n);
        if (k == 1) {
            long res = (long) 1e18;
            for (int i = 0; i < n; i++) {
                res = Math.min(res, Math.abs(-arr[i]));
            }
            System.out.println(res);
        } else {
            int j = 0;
            int window = k - 2;
            long diff = 0;
            long res = (long) 1e18;
            for (int i = 0; i < n - 1; i++, window--) {
                diff += arr[i + 1] - arr[i];
                if (window == 0) {
                    res = Math.min(res, Math.abs(arr[j]) + diff);
                    diff -= arr[j + 1] - arr[j];
                    j++;
                    window++;
                }
            }
            System.out.println(res);
        }
    }

    static final class Util {
        public static void shuffleSort(int[] x) {
            shuffle(x);
            Arrays.sort(x);
        }

        public static void shuffleSort(long[] x) {
            shuffle(x);
            Arrays.sort(x);
        }

        public static void shuffle(int[] x) {
            final Random r = new Random();

            for (int i = 0; i <= x.length - 2; i++) {
                final int j = i + r.nextInt(x.length - i);
                swap(x, i, j);
            }
        }

        public static void shuffle(long[] x) {
            final Random r = new Random();

            for (int i = 0; i <= x.length - 2; i++) {
                final int j = i + r.nextInt(x.length - i);
                swap(x, i, j);
            }
        }

        public static void swap(int[] x, int i, int j) {
            final int t = x[i];
            x[i] = x[j];
            x[j] = t;
        }

        public static void swap(long[] x, int i, int j) {
            final long t = x[i];
            x[i] = x[j];
            x[j] = t;
        }

        private Util() {}
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        private String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    //noinspection CallToPrintStackTrace
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        int[] nextIntArray(int n) {
            final int[] a = new int[n];
            for (int i = 0; i < n; i++) { a[i] = nextInt(); }
            return a;
        }

        long[] nextLongArray(int n) {
            final long[] a = new long[n];
            for (int i = 0; i < n; i++) { a[i] = nextLong(); }
            return a;
        }
    }
}


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int N = in.nextInt();
            int K = in.nextInt();
            int[] x = new int[N + 1];
            for (int i = 0; i < N; i++) {
                x[i] = in.nextInt();
            }
            x[N] = 0;
            Arrays.sort(x);

            int index0 = 0;
            for (int i = 0; i < N + 1; i++) {
                if (x[i] == 0) {
                    index0 = i;
                    break;
                }
            }

            int start = index0 - K;
            int end = index0 + K;
            int Start = Math.max(0, start);
            int End = Math.min(N, end);

            int min = (int) 1e9;
            if (Start == start) {
                min = Math.min(min, -1 * x[Start]);
            }
            for (int i = Start + 1; i <= index0; i++) {
                if (i + K < x.length) {
                    min = Math.min(min, -2 * x[i] + x[i + K]);
                }
            }
            for (int i = index0; i < End; i++) {
                if (i - K >= 0) {
                    min = Math.min(min, -x[i - K] + 2 * x[i]);
                }
            }
            if (End == end) {
                min = Math.min(min, x[End]);
            }

            System.out.println(min);
        }
    }
}


//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	int pn = 1;
	if (ci - cn + 16 > cm) {
		if ((ct = getcha()) == '-') { pn = -1; ct = getcha(); }
		A = ct - '0';
		while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
	else {
		if ((ct = *ci++) == '-') { pn = -1; ct = *ci++; }
		A = ct - '0';
		while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint(), K = getint();
	int x[100000];
	rep(i, N) x[i] = getint();

	int saishou = 300000001;
	rep(i, N) {
		if (i + K <= N) {
			int kari = abs(x[i]) + abs(x[i + K - 1] - x[i]);
			saishou = min(kari, saishou);
		}
		if (i - K + 1 >= 0) {
			int kari = abs(x[i]) + abs(x[i - K + 1] - x[i]);
			saishou = min(kari, saishou);
		}
	}
	printf("%d", saishou);

	Would you please return 0;
}


#include <bits/stdc++.h>
using namespace std;
namespace fastIO{
	#define BUF_SIZE 100000
	#define OUT_SIZE 100000
	//fread->read
	bool IOerror=0;
//	inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;}
	inline char nc(){
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend){
			p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin);
			if(pend==p1){IOerror=1;return -1;}
		}
		return *p1++;
	}
	inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';}
	template<class T> inline bool read(T &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(sign)x=-x;
		return true;
	}
	inline bool read(double &x){
		bool sign=0;char ch=nc();x=0;
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		if(ch=='-')sign=1,ch=nc();
		for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
		if(ch=='.'){
			double tmp=1; ch=nc();
			for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0');
		}
		if(sign)x=-x;
		return true;
	}
	inline bool read(char *s){
		char ch=nc();
		for(;blank(ch);ch=nc());
		if(IOerror)return false;
		for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch;
		*s=0;
		return true;
	}
	inline bool read(char &c){
		for(c=nc();blank(c);c=nc());
		if(IOerror){c=-1;return false;}
		return true;
	}
	template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);}
	#undef OUT_SIZE
	#undef BUF_SIZE
};
using namespace fastIO;
/************* debug begin *************/
string to_string(string s){return '"'+s+'"';}
string to_string(const char* s){return to_string((string)s);}
string to_string(const bool& b){return(b?"true":"false");}
template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();}
template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";}
template<class A>string to_string(const vector<A> v){
	int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}";
	return res;
}
void debug_out(){puts("");}
template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);}
#ifdef tokitsukaze
#define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__);
#else
#define debug(...) 233;
#endif
/*************  debug end  *************/
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define mem(a,b) memset((a),(b),sizeof(a))
#define MP make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
using namespace __gnu_cxx;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef vector<int> VI;
typedef vector<ll> VL;
void go();
int main(){
	#ifdef tokitsukaze
		freopen("TEST.txt","r",stdin);
	#endif
	go();return 0;
}
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-6;
const int MAX=1e5+10;
const ll mod=1e9+7;
/*********************************  head  *********************************/
ll a[MAX];
void go()
{
	ll ans,n,i,j,k;
	while(read(n,k))
	{
		for(i=0;i<n;i++) read(a[i]);
		ans=LLINF;
		for(i=0,j=0;i+k-1<n;i++)
		{
			while(j<n&&j-i+1<k) j++;
			if((a[i]>=0&&a[j]>=0)||(a[i]<=0&&a[j]<=0)) ans=min(ans,max(abs(a[i]),abs(a[j])));
			else
			{
				ans=min(ans,2*abs(a[i])+abs(a[j]));
				ans=min(ans,2*abs(a[j])+abs(a[i]));
			}
		}
		printf("%lld\n",ans);
	}
}


#ifndef LOCAL
#pragma GCC optimize ("O3")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target ("avx")
#endif

#include <vector>
#include <set>
#include <map>
#include <tuple>
#include <queue>
#include <stack>
#include <bitset>
#include <functional>
#include <algorithm>
#include <utility>
#include <numeric>
#include <iostream>
#include <cmath>
#include <cassert>
#include <cstring>

using namespace std;

using ll = long long;
using VI = vector<int>;
using VVI = vector<vector<int>>;
using VLL = vector<ll>;
using VVLL = vector<vector<ll>>;
using VB = vector<bool>;
using PII = pair<int, int>;
using PLL = pair<ll, ll>;
template <typename T>
using minheap = priority_queue<T, vector<T>, greater<T>>;
const int INF = 1000000007;
const ll INF_LL = 1'000'000'000'000'000'007;

#define __overload3(_1, _2, _3, name,...) name
#define rep(...) __overload3(__VA_ARGS__, repFromUntil, repUntil, repeat)(__VA_ARGS__)
#define repeat(times) repFromUntil(_name##__LINE__, 0, times)
#define repUntil(name, times) repFromUntil(name, 0, times)
#define repFromUntil(name, from, until) for (int name = from, name##__until = (until); name < name##__until; name++)
#define repr(...) __overload3(__VA_ARGS__, reprFromUntil, reprUntil, repeat)(__VA_ARGS__)
#define reprUntil(name, times) reprFromUntil(name, 0, times)
#define reprFromUntil(name, from, until) for (int name = until - 1, name##__from = (from); name >= name##__from; name--)

#define EXIT(out) do { OUT(out); exit(0); } while (0)

#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define fs first
#define sn second

#ifdef LOCAL
#define debug(v) do {debugos << "L" << __LINE__ << " " << #v << " > ";debugos<<(v)<<newl;} while (0)
#define debugv(v) do {debugos << "L" << __LINE__ << " " << #v << " > ";for(auto e:(v)){debugos<<e<<" ";}debugos<<newl;} while (0)
#define debuga(m,w) do {debugos << "L" << __LINE__ << " " << #m << " > ";for(int x=0;x<(w);x++){debugos<<(m)[x]<<" ";}debugos<<newl;} while (0)
#define debugaa(m,h,w) do {debugos << "L" << __LINE__ << " " << #m << " > \n";for(int y=0;y<(h);y++){for(int x=0;x<(w);x++){debugos<<(m)[y][x]<<" ";}debugos<<newl;}} while (0)
#else
#define debug(v) do {v;} while (0)
#define debugv(v) do; while (0)
#define debuga(m,w) do; while (0)
#define debugaa(m,h,w) do; while (0)
#endif

#define newl "\n"
constexpr int dr[] = {1,-1,0,0};  // LRUD
constexpr int dc[] = {0,0,1,-1};

bool inside(int r, int c, int H, int W) {
  return 0 <= r and r < H and 0 <= c and c < W;
}

template <typename T, typename U> bool chmin(T& var, U x) {
  if (var > x) {
    var = x;
    return true;
  } else return false;
}

template <typename T, typename U> bool chmax(T& var, U x) {
  if (var < x) {
    var = x;
    return true;
  } else return false;
}

template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); }

ll power(ll e, int t, ll mod = INF_LL) {
  ll res = 1;
  while (t) {
    if (t&1) res = (res * e) % mod;
    t >>= 1;
    e = (e * e) % mod;
  }
  return res;
}

template <typename T> T divceil(T m, T d) {
  assert(m >= 0 and d > 0);
  return (m+d-1)/d;
}

template<typename T>
vector<T> make_v(size_t a, T b) { return vector<T>(a, b); }

template<typename... Ts>
auto make_v(size_t a, Ts... ts) {
  return vector<decltype(make_v(ts...))>(a, make_v(ts...));
}

string operator*(const string& s, int times) {
  string res = "";
  rep(times) res += s;
  return res;
}

class MyScanner {
public:
  int offset = 0;
  char nc(){
#ifdef LOCAL
    return getchar();
#else
    static char buf[100000],*L=buf,*R=buf;
    return L==R&&(R=(L=buf)+fread(buf,1,100000,stdin),L==R)?EOF:*L++;
#endif
  }
  template <typename T> void input_integer(T& var) {
    var = 0; T sign = 1;
    int cc = nc();
    for (; cc<'0' || '9'<cc; cc = nc())
      if (cc == '-') sign = -1;
    for (; '0' <= cc && cc <= '9'; cc = nc())
      var = (var << 3) + (var << 1) + cc - '0';
    var = var * sign; var += offset;
  }
  int c() { char c; while (c = nc(), c == ' ' or c == '\n'); return c; }
  MyScanner& operator>>(char& var) { var = c(); return *this; }
  MyScanner& operator>>(int& var) { input_integer<int>(var); return *this; }
  MyScanner& operator>>(ll& var) { input_integer<ll>(var); return *this; }
  MyScanner& operator>>(string& var) {
    var = ""; int cc = nc();
    for (; !isvisiblechar(cc); cc = nc());
    for (; isvisiblechar(cc); cc = nc())
      var.push_back(cc);
    return *this;
  }
  template <typename T>
  operator T() { T x; *this >> x; return x; }
  template <typename T>
  void operator()(T &t) { *this >> t; }
  template <typename T, typename... Ts>
  void operator()(T &t, Ts &...ts) { *this >> t; this->operator()(ts...); }
  template <typename Iter>
  void iter(Iter first, Iter last) { while (first != last) *this >> *first, first++; }
  VI vi(int n) { VI res(n); iter(all(res)); return res; }
  VVI vvi(int n, int m) { VVI res(n); rep(i, n) res[i] = vi(m); return res; }
  VLL vll(int n) { VLL res(n); iter(all(res)); return res; }
  VVLL vvll(int n, int m) { VVLL res(n); rep(i, n) res[i] = vll(m); return res; }
  template <typename T>
  vector<T> v(int n) { vector<T> res(n); iter(all(res)); return res; }
private:
  int isvisiblechar(int c) { return 0x21 <= c && c <= 0x7E; }
} IN, IN1{-1};

class MyPrinter {
public:
  template <typename T>
  void output_integer(T var) {
    if (var == 0) { putchar('0'); return; }
    if (var < 0) putchar('-'), var = -var;
    char stack[32]; int stack_p = 0;
    while (var) stack[stack_p++] = '0' + (var % 10), var /= 10;
    while (stack_p) putchar(stack[--stack_p]);
  }
  MyPrinter& operator<<(char c) { putchar(c); return *this; }
  MyPrinter& operator<<(double x) { printf("%.10f\n", x); return *this; }
  template <typename T> MyPrinter& operator<<(T var) { output_integer<T>(var); return *this; }
  MyPrinter& operator<<(char* str_p) { while (*str_p) putchar(*(str_p++)); return *this; }
  MyPrinter& operator<<(const char* str_p) { while (*str_p) putchar(*(str_p++)); return *this; }
  MyPrinter& operator<<(const string& str) {
    const char* p = str.c_str();
    const char* l = p + str.size();
    while (p < l) putchar(*p++);
    return *this;
  }
  template <typename T>
  void operator()(T x) { *this << x << newl; }
  template <typename T, typename... Ts>
  void operator()(T x, Ts ...xs) { *this << x << " "; this->operator()(xs...); }
  template <typename Iter>
  void iter(Iter s, Iter t) {
    if (s == t) *this << "\n";
    else {
      for (; s != t; s++) {
        *this << *s << " \n"[next(s, 1) == t];
      }
    }
  }
  template <typename Range>
  void range(const Range& r) { iter(begin(r), end(r)); }
} OUT;

class DebugPrint {
public:
  template <typename T>
  DebugPrint& operator <<(const T& v) {
#ifdef LOCAL
    cerr << v;
#endif
    return *this;
  }
} debugos;

template <typename OutStream, typename T, typename U>
OutStream& operator<<(OutStream& out, const pair<T, U>& var) {
  return out << var.first << " " << var.second;
}
template <typename OutStream, typename Tuple, size_t I, size_t N,
          enable_if_t<I == N>* = nullptr>
OutStream& tuple_impl(OutStream& out, const Tuple& var) {
  return out;
}
template <typename OutStream, typename Tuple, size_t I, size_t N,
          enable_if_t<I != N>* = nullptr>
OutStream& tuple_impl(OutStream& out, const Tuple& var) {
  out << get<I>(var) << " ";
  return tuple_impl<OutStream, Tuple, I+1, N>(out, var);
}
template <typename OutStream, typename... Ts>
OutStream& operator<<(OutStream& out, const tuple<Ts...>& var) {
  return tuple_impl<OutStream, tuple<Ts...>, 0, sizeof...(Ts)>(out, var);
}
template <typename InStream, typename T, typename U>
InStream& operator>>(InStream& in, pair<T, U>& var) {
  return in >> var.first >> var.second;
}
template <typename InStream, typename Tuple, size_t I, size_t N,
          enable_if_t<I == N>* = nullptr>
InStream& tuple_impl(InStream& in, Tuple& var) {
  return in;
}
template <typename InStream, typename Tuple, size_t I, size_t N,
          enable_if_t<I != N>* = nullptr>
InStream& tuple_impl(InStream& in, Tuple& var) {
  in >> get<I>(var);
  return tuple_impl<InStream, Tuple, I+1, N>(in, var);
}
template <typename InStream, typename... Ts>
InStream& operator>>(InStream& in, tuple<Ts...>& var) {
  return tuple_impl<InStream, tuple<Ts...>, 0, sizeof...(Ts)>(in, var);
}

int main() {
  int n = IN, k = IN;
  auto x = IN.vll(n);
  VLL neg, pos;
  rep(i, n) (x[i] < 0 ? neg : pos).push_back(x[i]);
  neg.push_back(0);
  reverse(all(neg));
  reverse(all(pos)); pos.push_back(0); reverse(all(pos));
  ll res = INF_LL;
  rep(left, k+1) if (left < neg.size() and k-left < pos.size())
    chmin(res, min(-neg[left]*2+pos[k-left], -neg[left]+pos[k-left]*2));
  OUT(res);
}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main() {
  ll a,b;
  cin>>a>>b;
  vector<ll>vec(a+1);
  ll c=0;
  vec.at(0)=0;
  for(ll i=0;i<a;i++){
    cin>>vec.at(i+1);
    if(vec.at(i+1)<0){
      c+=1;
    }
  }
  sort(vec.begin(),vec.end());
  ll d=1000000000000000;
  for(ll i=0;i<=c;i++){
    if(a-c<b-i){
      continue;
    }
    else{
      d=min(d,min(-vec.at(c-i),vec.at(c+b-i))-vec.at(c-i)+vec.at(c+b-i));
    }
  }
  cout<<d<<endl;

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
const long long INF = 1LL << 60;
const ll C = 1000000000+7;

int main() {
    int N, K;
    cin >> N >> K;
    vector<int> x(N);
    for(int i=0; i<N; i++) cin >> x[i];

    ll min_time1 = abs(x[0]) + abs(x[K-1] - x[0]);
    ll min_time2 = abs(x[K-1]) +  abs(x[K-1] - x[0]);
    ll min_time = min(min_time1, min_time2);
    for(int i=0; i<N-K; i++) {
        ll t1 = abs(x[i]) + abs(x[i+K-1] - x[i]);
        ll t2 = abs(x[i + K - 1]) + abs(x[i+K-1] - x[i]);
        min_time = min(min_time, min(t1, t2));
    }
    cout << min_time << endl;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
const long long INF = 1LL << 60;
const ll C = 1000000000+7;

int main() {
    int N, K;
    cin >> N >> K;
    vector<int> x(N);
    for(int i=0; i<N; i++) cin >> x[i];

    ll min_time = abs(x[0]) + abs(x[K-1] - x[0]);
    for(int i=0; i<N-K; i++) {
        ll t1 = abs(x[i]) + abs(x[i+K-1] - x[i]);
        ll t2 = abs(x[i + K - 1]) + abs(x[i+K-1] - x[i]);
        min_time = min(min_time, min(t1, t2));
    }
    cout << min_time << endl;
}


// AtCoder ABC107: C - Candles
// 2019.9.11 bal4u

#include <stdio.h>

#if 1
int getchar_unlocked(void);
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif

int in() {  // 整数の入力
	int n = 0, c = gc();
	if (c == '-') {	c = gc();
		do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
		return -n;
	}
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

#define MIN(a,b)  ((a)<=(b)?(a):(b))
#define MAX(a,b)  ((a)>=(b)?(a):(b))
#define ABS(a)    ((a)>=0?(a):-(a))
int N, K;
int x[100005];

// 見つからなければ、一つ小さい要素を返す
int bs(int t)
{
	int m, l = 0, r = N;

    while (l < r) {
        m = (l+r) >> 1;
        if (x[m] <= t) l = m + 1; else r = m;
    }
	return l-1;
}

int main()
{
	int i, ans, t;

	N = in(), K = in();
	for (i = 0; i < N; i++) x[i] = in();
	if (x[0] >= 0) { printf("%d\n", x[K-1]); return 0; }

	ans = 0x7fffffff;
	i = bs(0); while (N-i < K) i--;
	for ( ; i >= 0; i--) {
		t = x[K+i-1]-x[i] + MIN(ABS(x[K+i-1]), ABS(x[i]));
		if (t < ans) ans = t;
	}
	printf("%d\n", ans);
	return 0;
}


//q1
// pactice

#pragma warning(disable:4996)
#pragma GCC diagnostic ignored "-Wunused-result"
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define MAX_NUMBER 100000
#define MAX_STRING 1000000

	int anNumber[MAX_NUMBER];
	int anMinusNumber[MAX_NUMBER];
	char sInput[MAX_STRING+1]="";

int main() {

	char* psInput=NULL;
	int nNumberOfNumber=0;
	int nQuotaNumber=0;

	int nMinChamp=1100000000;
	int nMinTemp=1100000000;
	int nMPChangedPos=-1;
	int nMinusCount=0;
	int nPlusCount=0;

	int i=0;
	int nTemp=0;
	int nPatternNo=0;

	for(i=0;i<MAX_NUMBER;i++){
		anNumber[i]=0;
	}
	// read line 1
	gets(sInput);
	psInput = strtok(sInput," ");
	nNumberOfNumber=atoi(psInput);
	psInput = strtok(NULL," ");
	nQuotaNumber=atoi(psInput);

	// read line 2
	gets(sInput);
	psInput = strtok(sInput," ");
	for (i=0;i<nNumberOfNumber;i++){
		nTemp=atoi(psInput);
		anNumber[i]=nTemp;
		if(nTemp<0){
			nMinusCount++;
		} else if (nTemp>0){
			nPlusCount++;
			if(nMPChangedPos==-1){
				if(nMinusCount>0){
					nMPChangedPos=i;
				}
			}
		} else {
			nQuotaNumber--;
		}
		psInput = strtok(NULL," ");
	}
	if (nQuotaNumber==0){
		printf("0\n");
	} else {
		if (nMinusCount==0&&nPlusCount>0){
			printf("%d\n",abs(anNumber[nQuotaNumber-1]));
		} else if (nMinusCount>0&&nPlusCount==0){
			printf("%d\n",abs(anNumber[nNumberOfNumber-nQuotaNumber]));
		} else {
			for(nPatternNo=0;nPatternNo<nQuotaNumber;nPatternNo++){
				if(nPatternNo==0){
					//左にだけ走る
					if(nMinusCount>=nQuotaNumber){
						nMinTemp=abs(anNumber[nMPChangedPos-nQuotaNumber]);
						if(nMinTemp<nMinChamp){
							nMinChamp=nMinTemp;
						}
					}
					//右にだけ走る
					if(nPlusCount>=nQuotaNumber){
						nMinTemp=abs(anNumber[nQuotaNumber-1+nMPChangedPos]);
						if(nMinTemp<nMinChamp){
							nMinChamp=nMinTemp;
						}
					}
				} else {
					//左に走ってから右に折り返す
					if(nMinusCount>=nPatternNo&&nPlusCount>=(nQuotaNumber-nPatternNo)){
						//左に走った分
						nMinTemp=abs(anNumber[nMPChangedPos-nPatternNo]*2);
						//右に走った分
						nMinTemp=nMinTemp+abs(anNumber[(nQuotaNumber-nPatternNo)-1+nMPChangedPos]);
						if(nMinTemp<nMinChamp){
							nMinChamp=nMinTemp;
						}
					}
					//右に走ってから左に折り返す
					if(nPlusCount>=nPatternNo&&nMinusCount>=(nQuotaNumber-nPatternNo)){
						//右に走った分
						nMinTemp=abs(anNumber[nPatternNo-1+nMPChangedPos]*2);
						//左に走った分
						nMinTemp=nMinTemp+abs(anNumber[nMPChangedPos-(nQuotaNumber-nPatternNo)]);
						if(nMinTemp<nMinChamp){
							nMinChamp=nMinTemp;
						}
					}
				}
			}
			printf("%d",nMinChamp);
		}
	}

	return 0;
}


#include <stdio.h>
#include <stdlib.h>

int N, K;
int x[114514];

int main(void) {
	int i;
	int mizuhasu = 1111111111;
	if (scanf("%d%d", &N, &K) != 2) return 1;
	for (i = 0; i < N; i++) {
		if (scanf("%d", &x[i]) != 1) return 1;
	}
	for (i = K - 1; i < N; i++) {
		int l = i - (K - 1), r = i;
		int satorina;
		satorina = abs(x[l]);
		if (abs(x[r]) < satorina) satorina = abs(x[r]);
		satorina += x[r] - x[l];
		if (satorina < mizuhasu) mizuhasu = satorina;
	}
	printf("%d\n", mizuhasu);
	return 0;
}


i;j;x[9<<14];m=9<<25;main(){
for(;~scanf("%d",x+i++););
for(;j<x[0]-x[1]+1;j++)m=fmin(x[j+x[1]+1]-x[j+2]+fmin(abs(x[j+2]),abs(x[j+x[1]+1])),m);
printf("%d",m);


#include <stdio.h>
int main(void){
    int x[9<<14];
    int i=0;
    int j=0;
    int min=9<<25;

    for(;~scanf("%d",x+i++););
    for(;j<x[0]-x[1]+1;)min=fmin(x[j+x[1]+1]-x[j+2]+fmin(abs(x[j+2]),abs(x[j+++x[1]+1])),min);
    printf("%d",min);
}


#include <stdio.h>
int main(void){
    int x[9<<14];
    int i=0;
    int j=0;
    int min=9<<25;

    for(;~scanf("%d",x+i);i++);
    for(j=2;j<x[0]-x[1]+3;j++)min=fmin(x[j+x[1]-1]-x[j]+fmin(abs(x[j]),abs(x[j+x[1]-1])),min);

    printf("%d",min);


function Main(input) {
  input = input.split("\n");
  var n = parseInt(input[0].split(" ")[0]);
  var k = parseInt(input[0].split(" ")[1]);
  x = new Array(n).fill(0);
  tmp = input[1].split(" ");
  var plus=0;
  var minus=0;
  for(i=0;i<n;i++){
    x[i]=parseInt(tmp[i]);
    if(x[i]>0){
      plus++;
    }else if(x[i]<0){
      minus++;
    }
  }
  var ans=Math.pow(10,9)+7;
  if(x.indexOf(0)!=-1){
    n-=1;
    k-=1;
    x.splice(x.indexOf(0),1);
  }
  if(x.length==0){
    ans=0;
  }else if(minus==0){
    ans=x[k-1];
  }else if(plus==0){
    ans=Math.abs(x[n-k]);
  }else if(n!=2){
    for(i=0;i<n-k+1;i++){
      if(x[i]<0&&x[i+k-1]>0){
        ans=Math.min(ans,Math.abs(x[i])*2+x[i+k-1],Math.abs(x[i])+x[i+k-1]*2);
      }else if(i==minus-k){
        ans=Math.min(ans,Math.abs(x[i]));
      }else if(i==minus){
        ans=Math.min(ans,x[i+k-1]);
      }
    }
  }else{
    ans=Math.min(Math.abs(x[0]),x[1]);
  }
  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  var ary = input.split("\n");
  var nums = ary[0].split(" ");
  var n = parseInt(nums[0], 10);
  var k = parseInt(nums[1], 10);
  var x = ary[1].split(" ").map(i => parseInt(i, 10));
  var minTime = null;

  for (var i = 0; i < n - k + 1; i++) {
    var time = calcMinTime(i, i + k - 1, x);
    if (minTime === null || time < minTime) {
      minTime = time;
    }
  }
  console.log(minTime);
}

function calcMinTime(i, j, x) {
  var a = Math.abs(x[i]) + Math.abs(x[j] - x[i]);
  var b = Math.abs(x[j]) + Math.abs(x[j] - x[i]);
  return Math.min(a, b);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    input = input.split("\n");
    var nk = input[0].split(" ");
    var n = parseInt(nk[0], 10);
    var k = parseInt(nk[1], 10);
    var X = input[1].split(" ").map(x => parseInt(x, 10));
    var zeroInd = -1;
    for (var i = 0; i < n; i++) {
        if (X[i] >= 0) {
            zeroInd = i;
            break;
        }
    }
    if (X[n-1] < 0) {
        zeroInd = n;
    }
    var left = Math.max(zeroInd - k, 0);
    var right = Math.min(zeroInd + k, n);
    var sofar = 1000000001;
    for (var i = left; i < right-k+1; i++) {
        var leftHalf = 0;
        var rightHalf = 0;
        if (i < zeroInd) {
            leftHalf = Math.abs(X[i]);
            rightHalf = Math.max(X[i+k-1], 0);
        } else if (i >= zeroInd) {
            leftHalf = 0;
            rightHalf = X[i+k-1];
        }
        var candid = Math.min(leftHalf*2+rightHalf, leftHalf+rightHalf*2)
        sofar = Math.min(sofar, candid);
    }
    console.log(sofar);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var K = one[1];
	var list = nextIntArray();
	var ruiseki = [0];
	var startIndex = list.indexOf(0);
	var output = Math.pow(10,16);
	if(startIndex != -1){
		//0がある
		K--;
		if(K == 0){
			myout(0);
			return;
		}
	}else if(list[0] > 0){
		//始点が左端
		myout(Math.abs(list[K - 1]));
		return;
	}else if(list[N - 1] < 0){
		//始点が右端
		myout(Math.abs(list[N - K]));
		return;
	}else{
		var tmpList = [];
		var isZero = false;
		for(var i = 0; i < N; i++){
			if(!isZero && list[i] > 0){
				tmpList.push(0);
				isZero = true;
				startIndex = i;
			}
			tmpList.push(list[i]);
		}
		list = tmpList;
		N++;
	}
	for(var i = 0; i < N - 1; i++){
		ruiseki.push(ruiseki[ruiseki.length - 1] + Math.abs(Math.abs(list[i]) - Math.abs(list[i + 1])));
	}
	var left = startIndex - 1;
	var leftCount = K;
	var right = startIndex + 1;
	var rightCount = K;
	while(left >= 0 && leftCount > 0){
		var tmpSum = ruiseki[startIndex] - ruiseki[left];
		if(startIndex - left < K){
			tmpSum += ruiseki[startIndex] - ruiseki[left];//折り返し
			tmpSum += ruiseki[startIndex + (K - (startIndex - left))] - ruiseki[startIndex];
		}
		output = Math.min(output, tmpSum);
		left--;
		leftCount--;
	}

	while(right < N && rightCount > 0){
		var tmpSum = ruiseki[right] - ruiseki[startIndex];
		if(right - startIndex < K){
			tmpSum += ruiseki[right] - ruiseki[startIndex];//折り返し
			tmpSum += ruiseki[startIndex] + ruiseki[startIndex - (K - (right - startIndex))];
		}
		output = Math.min(output, tmpSum);
		right++;
		rightCount--;
	}
	myout(output);
}


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var K = one[1];
	var list = nextIntArray();
	var ruiseki = [0];
	var startIndex = list.indexOf(0);
	var output = Math.pow(10,15);
	if(startIndex != -1){
		//0がある
		K--;
		if(K == 0){
			myout(0);
			return;
		}
	}else if(list[0] > 0){
		//始点が左端
		myout(Math.abs(list[K - 1]));
		return;
	}else if(list[N - 1] < 0){
		//始点が右端
		myout(Math.abs(list[N - K]));
		return;
	}else{
		var tmpList = [];
		var isZero = false;
		for(var i = 0; i < N; i++){
			if(!isZero && list[i] > 0){
				tmpList.push(0);
				isZero = true;
				startIndex = i;
			}
			tmpList.push(list[i]);
		}
		list = tmpList;
		N++;
	}
	for(var i = 0; i < N - 1; i++){
		ruiseki.push(ruiseki[ruiseki.length - 1] + Math.abs(Math.abs(list[i]) - Math.abs(list[i + 1])));
	}
	var left = startIndex - 1;
	var leftCount = K;
	var right = startIndex + 1;
	var rightCount = K;
	while(left >= 0 && leftCount > 0){
		var tmpSum = ruiseki[startIndex] - ruiseki[left];
		if(startIndex - left < K){
			tmpSum += ruiseki[startIndex] - ruiseki[left];//折り返し
			tmpSum += ruiseki[startIndex + (K - (startIndex - left))] - ruiseki[startIndex];
		}
		output = Math.min(output, tmpSum);
		left--;
		leftCount--;
	}

	while(right < N && rightCount > 0){
		var tmpSum = ruiseki[right] - ruiseki[startIndex];
		if(right - startIndex < K){
			tmpSum += ruiseki[right] - ruiseki[startIndex];//折り返し
			tmpSum += ruiseki[startIndex] + ruiseki[startIndex - (K - (right - startIndex))];
		}
		output = Math.min(output, tmpSum);
		right++;
		rightCount--;
	}
	myout(output);
}


"use strict";

const absOfArray = array => {
    const N = array.length;
    const temp = [];

    if(array.length === 1) {
        return array[0];
    }

    for(let i=1; i<N; i++) {
        temp.push(Math.abs(array[i-1] - array[i]));
    }

    return temp.reduce((m,n)=>m+n);
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    let K = parseInt(arg[0].split(" ")[1]);
    const X = arg[1].split(" ").map(n=>parseInt(n));

    const minus = X.filter(n=>n<0).slice(-K);
    const plus  = X.filter(n=>n>0).slice(0, K);

    const newX = minus.concat([0]).concat(plus);

    let memo = absOfArray(newX.slice(0, K + 1));
    let answer = memo;

    // console.log(minus);
    // console.log(plus);
    // console.log(newX);

    if(K > newX.length) {
        console.log(memo);
        return;
    }

    for(let i=1; i<=newX.length-K-1; i++) {
        memo -= Math.abs(newX[i-1] - newX[i]);
        memo += Math.abs(newX[i + K] - newX[i + K - 1]);

        // console.log("newX[i + K]:" + newX[i + K])
        // console.log("新しい値:" + memo)

        answer = Math.min(memo, answer);
    }

    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// by syu
package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

var in = NewScanner(os.Stdin, 0)

func main() {
	N, K := in.Int(), in.Int()
	x := in.ArrayInt32(N)
	var min int32 = math.MaxInt32
	for i := 0; i < N-K+1; i++ {
		a, b := x[i], x[i+K-1]
		sum := Min232(Abs32(a), Abs32(b)) + b - a
		if sum < min {
			min = sum
		}
	}
	Pln(min)
}

type Scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader, max int) *Scanner {
	s := bufio.NewScanner(r)
	s.Split(scanWords)
	if max <= 0 {
		max = 1048576
	}
	s.Buffer([]byte{}, max)
	return &Scanner{s}
}
func (s *Scanner) Int() int {
	s.Scan()
	i, e := strconv.ParseInt(s.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return int(i)
}
func (s *Scanner) Int32() int32 {
	s.Scan()
	i, e := strconv.ParseInt(s.Text(), 10, 32)
	if e != nil {
		panic(e)
	}
	return int32(i)
}
func (s *Scanner) ArrayInt32(n int) []int32 {
	r := make([]int32, n)
	for i := 0; i < n; i++ {
		r[i] = s.Int32()
	}
	return r
}
func isSpace(b byte) bool {
	return b == ' ' || b == '\n' || b == '\r' || b == '\t'
}
func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	start := 0
	for start < len(data) && isSpace(data[start]) {
		start++
	}
	for i := start; i < len(data); i++ {
		if isSpace(data[i]) {
			return i + 1, data[start:i], nil
		}
	}
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	return start, nil, nil
}
func Min232(a, b int32) int32 {
	if a < b {
		return a
	}
	return b
}
func Abs32(n int32) int32 {
	y := n >> 31
	return (n ^ y) - y
}
func Pln(s ...interface{}) {
	fmt.Println(s...)
}


// by syu
package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

var in = NewScanner(os.Stdin, 0)

func main() {
	N, K := in.Int(), in.Int()
	x := in.ArrayInt(N)
	min := math.MaxInt64
	for i := 0; i < N-K+1; i++ {
		a, b := x[i], x[i+K-1]
		sum := Min2(Abs(a), Abs(b)) + b - a
		if sum < min {
			min = sum
		}
	}
	Pln(min)
}

type Scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader, max int) *Scanner {
	s := bufio.NewScanner(r)
	s.Split(scanWords)
	if max <= 0 {
		max = 1048576
	}
	s.Buffer([]byte{}, max)
	return &Scanner{s}
}
func (s *Scanner) Int() int {
	s.Scan()
	i, e := strconv.ParseInt(s.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return int(i)
}
func (s *Scanner) ArrayInt(n int) []int {
	r := make([]int, n)
	for i := 0; i < n; i++ {
		r[i] = s.Int()
	}
	return r
}
func isSpace(b byte) bool {
	return b == ' ' || b == '\n' || b == '\r' || b == '\t'
}
func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	start := 0
	for start < len(data) && isSpace(data[start]) {
		start++
	}
	for i := start; i < len(data); i++ {
		if isSpace(data[i]) {
			return i + 1, data[start:i], nil
		}
	}
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	return start, nil, nil
}
func Min2(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func Abs(n int) int {
	y := n >> 63
	return (n ^ y) - y
}
func Pln(s ...interface{}) {
	fmt.Println(s...)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

func intMin(x, y int) int {
	return int(math.Min(float64(x), float64(y)))
}

func main() {
	sc.Split(bufio.ScanWords)

	N, K := scanInt(), scanInt()
	X := make([]int, N)
	for i := 0; i < N; i++ {
		X[i] = scanInt()
	}

	ans := X[K-1] - X[0]
	for i := K; i < N; i++ {
		ans = intMin(ans, X[i]-X[i+1-K])
	}
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	var n, k int
	if scanner.Scan() {
		tmp := scanner.Text()
		n, _ = strconv.Atoi(tmp)
	}
	if scanner.Scan() {
		tmp := scanner.Text()
		k, _ = strconv.Atoi(tmp)
	}

	var xs []int
	for i := 0; i < n; i++ {
		if scanner.Scan() {
			tmp := scanner.Text()
			x, _ := strconv.Atoi(tmp)
			xs = append(xs, x)
		}
	}

	min := math.MaxInt32
	for i := 0; i < n-k+1; i++ {
		var v int
		if xs[i] >= 0 && xs[i+k-1] >= 0 {
			v = xs[i+k-1]
		} else if xs[i] <= 0 && xs[i+k-1] >= 0 {
			if math.Abs(float64(xs[i])) < math.Abs(float64(xs[i+k-1])) {
				v = xs[i+k-1] - 2*xs[i]
			} else {
				v = 2*xs[i+k-1] - xs[i]
			}
		} else {
			v = xs[i]
		}
		if min > v {

			min = v
		}
	}
	fmt.Println(min)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var (
	finv, inv, fac [MAX]int
)

func COM(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func init() {
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
	//sc.Split(bufio.ScanLines)
	sc.Split(bufio.ScanWords)
	//sc.Buffer([]byte{}, 100100)
}

const (
	MOD = 1000000007
	MAX = 510000
)

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	value int
	index int
	A, B  int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func FactoredPrimeNumber(num int) map[int]int {
	m := map[int]int{}
	return factor(m, num, 2)
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

func GCD(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

type UnionFind struct {
	par  []int
	size []int
}

func NewUnionFind(size int) *UnionFind {
	return new(UnionFind).init(size)
}

func (uf *UnionFind) init(size int) *UnionFind {
	uf.par = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.par[i] = i
		uf.size[i] = 1
	}
	return uf
}

func (uf *UnionFind) Unite(p int, q int) {
	rp := uf.Root(p)
	rq := uf.Root(q)
	if rp == rq {
		return
	}
	if uf.size[rp] < uf.size[rq] {
		uf.par[rp] = uf.par[rq]
		uf.size[rq] += uf.size[rp]
	} else {
		uf.par[rq] = uf.par[rp]
		uf.size[rp] += uf.size[rq]
	}
}

func (uf *UnionFind) Root(p int) int {
	for uf.par[p] == p {
		return p
	}
	uf.par[p] = uf.Root(uf.par[p])
	return uf.par[p]
}

func (uf *UnionFind) Size(p int) int {
	return uf.size[uf.Root(p)]
}

func (uf *UnionFind) Same(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	n, _ := strconv.Atoi(getStr())
	return n
}

func getStr() string {
	sc.Scan()
	return sc.Text()
}

func main() {
	N, K := getInt(), getInt()
	X := make([]int, N)
	for i := 0; i < N; i++ {
		X[i] = getInt()
	}
	min := int(1e16)
	for i := 0; i < N-K+1; i++ {
		t := 0
		O := X[i]
		if O < 0 {
			t += -O
		} else {
			t += O
		}
		G := X[i+K-1]
		D := G - O

		t += D
		if min > t {
			min = t
		}
	}
	fmt.Println(min)
}

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}


n, k = gets.split.map(&:to_i)
xs = gets.chomp.split.map(&:to_i)
min = Float::INFINITY
(0..n-k).each do |i|
  l = xs[i]
  r = xs[i+k-1]
  dist = (l.abs > r.abs) ? r.abs + r - l : l.abs + r - l
  if min > dist
    min = dist
  end
end

puts min


n, k = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
min = Float::INFINITY
0.upto(n - k) do |i|
  b = x[i + k - 1] - x[i]
  b += x[i + k - 1].abs > x[i].abs ? x[i].abs : x[i + k - 1].abs
  min = b if min > b
end
puts min


N, K = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)

ans = 10**9

bound =  x.bsearch_index{|e| e>=0}

#全部負の座標のとき
if bound == nil
  puts x[N-K].abs
  exit
end

#x>=0からi個，x<0からK-i個
0.upto(K) do |i|
  next if N-bound < i || bound < K-i
  right =
    if i != 0
      x[bound+i-1]
    else
      0
    end
  left =
    if i != K
      x[bound - (K-i)].abs
    else
      0
    end

  tmp =
    if right > left
      2*left + right
    else
      2*right + left
    end

  ans = tmp if tmp < ans
end

puts ans


n, k = gets.split.map &:to_i
l, r = gets.split.map(&:to_i).partition { |x| x < 0 }
d_min = 10**9

l_count = [0, l.size - k + 1].max
lr_count = [l.size, r.size, k-1].min

# 原点より左だけ
d_min = [d_min, -l[-k]].min if l.size >= k

# 左と右両方
lr_count.times do |i|
  x = -l[l_count + i]
  y = r[i]
  d_min = [d_min, x + y + [x, y].min].min
end

# 原点より右だけ
d_min = [d_min, r[k-1]].min if r.size >= k

p d_min


n, k = gets.split.map &:to_i
x = gets.split.map &:to_i
a_prev = [x[0].abs, x[k-1].abs].min
d_min = a_prev + (1...k).sum { |i| x[i] - x[i-1] }
(n - k).times do |i|
  d = d_min - a_prev - (x[i + 1] - x[i]) + (x[i + k] - x[i + k - 1])
  a_prev = [x[i + 1].abs, x[i + k].abs].min
  d += a_prev
  d_min = [d_min, d].min
end
p d_min


n, k = gets.split.map &:to_i
x = gets.split.map &:to_i
d_min = x[0].abs + (1...k).sum { |i| x[i] - x[i-1] }
(x.size - k).times do |i|
  d = d_min - x[i].abs - (x[i + 1] - x[i]) + x[i + 1].abs + (x[i + k] - x[i + k - 1])
  d_min = [d_min, d].min
end
p d_min


// ternary operation
#[allow(unused_macros)]
macro_rules! _if {
  ($_test:expr, $_then:expr, $_else:expr) => {
    if $_test { $_then } else { $_else }
  };
  ($_test:expr, $_pat:pat, $_then:expr, $_else:expr) => {
    match $_test {
      $_pat => $_then,
      _     => $_else
    }
  };
}

use std::io::{ stdin, stdout, Write };
use my::WriteWith;

#[inline(always)]
fn arc101_a() {
  let stdin  = stdin();
  let stdout = stdout();
  let (mut scanner, mut writer) = my::rw(12, stdin.lock(), stdout.lock());
  let mut itoa = my::ItoA::with_capacity(10);

  let n   = scanner.uint_until::<usize>(my::SP);
  let k   = scanner.uint_until::<usize>(my::LF);
  let vec = scanner.int_vec::<i32>(n, my::Direction::Horizontal);

  let len = vec.len() - k + 1;
  let mut v = Vec::with_capacity(len);
  for i in 0..len {
    let x = (vec[i + k - 1] - vec[i]).abs();
    let a = vec[i].abs();
    let b = vec[i + k - 1].abs();

    v.push(std::cmp::min(a, b) + x);
  }

  let &ans = v.iter().min().unwrap();

  writer.write_with(itoa.from_i32(ans), b"\n").unwrap();
  writer.flush().unwrap();
}

fn main() {
  arc101_a();
}

//------------------------------------------------------------------------
mod my {
  use std::hash::Hasher;
  use std::hash::BuildHasher;

  pub struct MyHasher(u64);

  impl Default for MyHasher {
    #[inline(always)]
    fn default() -> Self {
      MyHasher(0x00)
    }
  }

  impl BuildHasher for MyHasher {
    type Hasher = MyHasher;

    #[inline(always)]
    fn build_hasher(&self) -> Self::Hasher {
      Self::Hasher::default()
    }
  }

  impl Hasher for MyHasher {
    #[inline(always)]
    fn finish(&self) -> u64 {
      self.0
    }

    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
      self.0 = 0;
      for i in 0..bytes.len() {
        self.0 ^= (bytes[i] as u64) << (8 * (i % 8));
      }
    }
  }

  //----------------------------------------------------------------------
  use std::io::{ self, BufRead, BufReader, Write, BufWriter };
  use std::fmt::Debug;
  use std::ops::{ Add, Sub, Mul, Neg, Rem };
  use std::str::{ self, FromStr };
  use std::mem;

  const PLUS_SIGN : u8 = b'+';
  const MINUS_SIGN: u8 = b'-';
  const ASCII_0   : u8 = b'0';
  const ASCII_9   : u8 = b'9';

  pub const SP    : u8 = b' ';
  pub const LF    : u8 = b'\n';

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[inline(always)]
  pub fn rotate_right(ary: &mut [u8]) {
    if ary.len() <= 1 {
      return;
    }

    let len = ary.len() - 1;
    let tmp = ary[len];
    for i in 0..len {
      ary[len - i] = ary[len - i - 1];
    }
    ary[0] = tmp;
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn rotate_left(ary: &mut [u8]) {
    if ary.len() <= 1 {
      return;
    }

    let len = ary.len() - 1;
    let tmp = ary[0];
    for i in 0..len {
      ary[i] = ary[i + 1];
    }
    ary[len] = tmp;
  }

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[inline(always)]
  pub fn gcd<T>(x: T, y: T) -> T
    where T: Rem<Output=T> +
             Default +
             PartialEq +
             Copy +
             Debug
  {
    _if!(y == T::default(),
      x,
      gcd(y, x % y))
  }

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[inline(always)]
  pub fn intersection<T>(mut x: (T, T), mut y: (T, T)) -> Option<(T, T)>
    where T: PartialOrd +
             Copy +
             Debug
  {
    if x.0 > x.1 {
      mem::swap(&mut x.0, &mut x.1);
    }
    if y.0 > y.1 {
      mem::swap(&mut y.0, &mut y.1);
    }

    if x.0 >= y.1 || x.1 <= y.0 {
      return None;
    }

    if x.0 < y.0 {
      x.0 = y.0;
    }
    if x.1 > y.1 {
      x.1 = y.1;
    }

    Some(x)
  }

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[inline(always)]
  pub fn is_ascii_digit(b: u8) -> bool {
    _if!(b >= ASCII_0 && b <= ASCII_9,
      true,
      false)
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn is_ascii_uppercase(b: u8) -> bool {
    _if!(b >= b'A' && b <= b'Z',
      true,
      false)
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn is_ascii_lowercase(b: u8) -> bool {
    _if!(b >= b'a' && b <= b'z',
      true,
      false)
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn is_ascii_alphabetic(b: u8) -> bool {
    _if!(is_ascii_uppercase(b) || is_ascii_lowercase(b),
      true,
      false)
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn to_ascii_lowercase(b: u8) -> u8 {
    _if!(is_ascii_uppercase(b),
      b + 0x20,
      b)
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn to_ascii_uppercase(b: u8) -> u8 {
    _if!(is_ascii_lowercase(b),
      b - 0x20,
      b)
  }

  //----------------------------------------------------------------------
  pub trait WriteWith {
    fn write_with(&mut self, buf: &[u8], delim: &[u8]) -> io::Result<usize>;
  }

  impl<W> WriteWith for BufWriter<W>
    where W: io::Write
  {
    #[allow(dead_code)]
    #[inline(always)]
    fn write_with(&mut self, buf: &[u8], delim: &[u8]) -> io::Result<usize>
    {
      Ok(self.write(buf)? + self.write(delim)?)
    }
  } // impl<W> WriteWith for BufWriter<W>

  //----------------------------------------------------------------------
  macro_rules! pub_fn_ItoA_from_ty {
    (uint, $($name:ident => $_type:ty),*) => {$(
      #[allow(dead_code)]
      #[inline(always)]
      pub fn $name(&mut self, mut n: $_type) -> &[u8] {
        self.buf.clear();
        if n == 0 {
          self.buf.push(ASCII_0);
          return self.buf.as_slice();
        }

        while n > 0 {
          self.buf.push((n % 10) as u8 + ASCII_0);
          n /= 10;
        }
        self.buf.reverse();
        self.buf.as_slice()
      }
    )*};

    (int, $($name:ident => $_type:ty),*) => {$(
      #[allow(dead_code)]
      #[inline(always)]
      pub fn $name(&mut self, mut n: $_type) -> &[u8] {
        self.buf.clear();
        if n == 0 {
          self.buf.push(ASCII_0);
          return self.buf.as_slice();
        }

        let mut negative = false;
        if n.is_negative() {
          negative = true;
          n = n.abs();
        }

        while n > 0 {
          self.buf.push((n % 10) as u8 + ASCII_0);
          n /= 10;
        }
        if negative {
          self.buf.push(MINUS_SIGN);
        }
        self.buf.reverse();
        self.buf.as_slice()
      }
    )*};
  }

  #[derive(Debug)]
  pub struct ItoA {
    buf: Vec<u8>,
  }

  impl ItoA {
    #[allow(dead_code)]
    #[inline(always)]
    pub fn new() -> Self {
      ItoA {
        buf: Vec::new(),
      }
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn with_capacity(cap: usize) -> Self {
      ItoA {
        buf: Vec::with_capacity(cap),
      }
    }

    pub_fn_ItoA_from_ty!(
      uint,
      from_usize => usize,
      from_u8    => u8,
      from_u16   => u16,
      from_u32   => u32,
      from_u64   => u64
    );

    pub_fn_ItoA_from_ty!(
      int,
      from_isize => isize,
      from_i8    => i8,
      from_i16   => i16,
      from_i32   => i32,
      from_i64   => i64
    );
  } // impl ItoA

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[inline(always)]
  pub fn rw<R, W>(cap: usize, r: R, w: W) -> (Scanner<BufReader<R>>, BufWriter<W>)
    where R: BufRead,
          W: io::Write
  {
    (
      Scanner::with_capacity(cap, BufReader::new(r)),
      BufWriter::new(w)
    )
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn r<R>(cap: usize, r: R) -> Scanner<BufReader<R>>
    where R: BufRead
  {
    Scanner::with_capacity(cap, BufReader::new(r))
  }

  #[allow(dead_code)]
  #[inline(always)]
  pub fn w<W>(w: W) -> BufWriter<W>
    where W: io::Write
  {
    BufWriter::new(w)
  }

  //----------------------------------------------------------------------
  #[allow(dead_code)]
  #[derive(Debug)]
  pub enum Direction {
    Horizontal,
    Vertical
  }

  #[derive(Debug)]
  pub struct Scanner<R> {
    reader: R,
    buf   : Vec<u8>,
  }

  impl<R> Scanner<R>
    where R: BufRead
  {
    #[allow(dead_code)]
    #[inline(always)]
    pub fn new(reader: R) -> Self {
      Scanner {
        reader: reader,
        buf   : Vec::new(),
      }
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn with_capacity(cap: usize, reader: R) -> Self {
      Scanner {
        reader: reader,
        buf   : Vec::with_capacity(cap),
      }
    }

    //--------------------------------------------------------------------
    #[inline(always)]
    fn read_until(&mut self, delim: u8) -> usize {
      self.buf.clear();
      let mut len = self.reader.read_until(delim, &mut self.buf).unwrap();
      if len == 0 {
        return len;
      }

      len -= 1;
      if self.buf[len] == delim {
        self.buf.truncate(len);
      }
      len
    }

    //--------------------------------------------------------------------
    // s -> n
    #[allow(dead_code)]
    #[inline(always)]
    pub fn parse_until<T>(&mut self, delim: u8) -> T
      where T: FromStr + Debug,
            <T as FromStr>::Err: Debug
    {
      self.read_until(delim);
      unsafe { str::from_utf8_unchecked(&self.buf) }
        .parse()
        .unwrap()
    }

    //--------------------------------------------------------------------
    #[allow(dead_code)]
    #[inline(always)]
    pub fn byte_until(&mut self, delim: u8) -> Vec<u8> {
      self.read_until(delim);
      self.buf.clone()
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn string_until(&mut self, delim: u8) -> String {
      unsafe { String::from_utf8_unchecked(self.byte_until(delim)) }
    }

    //--------------------------------------------------------------------
    // s -> n
    #[allow(dead_code)]
    #[inline(always)]
    pub fn uint_until<T>(&mut self, delim: u8) -> T
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let len = self.read_until(delim);
      let mut n = T::default();
      if len == 0 {
        return n;
      }

      let mut i = 0;
      if self.buf[i] == PLUS_SIGN {
        i += 1;
      }

      for b in &self.buf[i..] {
        n = (n * T::from(10)) + T::from(b - ASCII_0);
      }

      n
    }

    // s -> n
    #[allow(dead_code)]
    #[inline(always)]
    pub fn int_until<T>(&mut self, delim: u8) -> T
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Neg<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let len = self.read_until(delim);
      let mut n = T::default();
      if len == 0 {
        return n;
      }

      let mut i = 0;
      let mut negative = false;
      if self.buf[i] == MINUS_SIGN {
        negative = true;
        i += 1;
      } else if self.buf[i] == PLUS_SIGN {
        i += 1;
      }

      for b in &self.buf[i..] {
        n = (n * T::from(10)) + T::from(b - ASCII_0);
      }

      _if!(negative,
        n.neg(),
        n)
    }

    //--------------------------------------------------------------------
    #[allow(dead_code)]
    #[inline(always)]
    pub fn uint_vec<T>(&mut self, n: usize, dir: Direction) -> Vec<T>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let delim = _if!(dir, Direction::Horizontal, SP, LF);
      let mut vec = Vec::with_capacity(n);
      for _ in 0..n - 1 {
        vec.push(self.uint_until(delim));
      }
      vec.push(self.uint_until(LF));
      vec
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn int_vec<T>(&mut self, n: usize, dir: Direction) -> Vec<T>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Neg<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let delim = _if!(dir, Direction::Horizontal, SP, LF);
      let mut vec = Vec::with_capacity(n);
      for _ in 0..n - 1 {
        vec.push(self.int_until(delim));
      }
      vec.push(self.int_until(LF));
      vec
    }

    // horizontal
    //
    // N
    // s1 s2 s3, ..., sN -> [n1, n2, n3, ..., nN]
    #[allow(dead_code)]
    #[inline(always)]
    pub fn uint_vec_h<T>(&mut self) -> Vec<T>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let n: usize = self.uint_until(LF);
      self.uint_vec(n, Direction::Horizontal)
    }

    // horizontal
    //
    // N
    // s1 s2 s3, ..., sN -> [n1, n2, n3, ..., nN]
    #[allow(dead_code)]
    #[inline(always)]
    pub fn int_vec_h<T>(&mut self) -> Vec<T>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Neg<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let n: usize = self.uint_until(LF);
      self.int_vec(n, Direction::Horizontal)
    }

    // N M
    // s11 s12 s13 ... s1M
    // s21 s22 s23 ... s2M
    // s31 s32 s33 ... s3M
    //   :
    // sN1 sN2 sN3 ... sNM
    // -> [
    //      [n11, n12, n13, ..., n1M],
    //      [n21, n22, n23, ..., n2M],
    //      [n31, n32, n33, ..., n3M],
    //          :
    //      [nN1, nN2, nN3, ..., nNM],
    //    ]
    #[allow(dead_code)]
    #[inline(always)]
    pub fn uint_vec2<T>(&mut self, n: usize, m: usize) -> Vec<Vec<T>>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let mut vec = Vec::with_capacity(n);
      for _ in 0..n {
        vec.push(self.uint_vec(m, Direction::Horizontal));
      }
      vec
    }

    // N M
    // s11 s12 s13 ... s1M
    // s21 s22 s23 ... s2M
    // s31 s32 s33 ... s3M
    //   :
    // sN1 sN2 sN3 ... sNM
    // -> [
    //      [n11, n12, n13, ..., n1M],
    //      [n21, n22, n23, ..., n2M],
    //      [n31, n32, n33, ..., n3M],
    //          :
    //      [nN1, nN2, nN3, ..., nNM],
    //    ]
    #[allow(dead_code)]
    #[inline(always)]
    pub fn int_vec2<T>(&mut self, n: usize, m: usize) -> Vec<Vec<T>>
      where T: Add<Output=T> +
               Sub<Output=T> +
               Mul<Output=T> +
               Neg<Output=T> +
               Default +
               From<u8> +
               Debug
    {
      let mut vec = Vec::with_capacity(n);
      for _ in 0..n {
        vec.push(self.int_vec(m, Direction::Horizontal));
      }
      vec
    }

  } // impl<R> Scanner<R>

} // mod my